为什么这段代码不打印“20”?
why this code doesn't print "20"?
void fun(int* x){
x=(int*)malloc(sizeof(int));
*x = 20;
}
int main(){
int y=31;
fun(&y);
printf(%d,y);
}
为什么这段代码编译成功了?
评论:是在Eclipse上编译的
我在网上看到问题:
x=(int*)malloc(sizeof(int));
为什么这个程序在运行时没有崩溃?
代码在语法上没有问题,因此可以编译。
y
的地址被传递给函数。函数中保存 y
地址的指针 x
被 malloc 分配的有效内存地址覆盖。一个 int 被写在那里而不是 y
因为指针的值被改变了。然后函数 returns(fun
中分配的内存执行 'leak')。
main中y
的值保持不变。
此程序的行为已定义。
嘿,你传递的是压入堆栈的变量 y 的地址副本。您只需通过分配 malloc
返回的地址并通过
将值 20 复制到该地址来操作指针(在指针被推送的位置)
*x = 20
这对 main
中的变量没有影响,即 y
如果你想让它打印 20 这可能会有所帮助
void fun(int** x){
*x=(int*)malloc(sizeof(int));
**x = 20;
}
int main(){
int *y;
fun(&y);
printf("%d",*y);
}
x=(int*)malloc(sizeof(int)); //x point to a new addr.
*x = 20; // change value of new pointer
删除行x=(int*)malloc(sizeof(int));
,就可以了。
我想你想做的是改变 main
函数中变量 y
的地址。您不能通过将 y
的地址值传递给函数来做到这一点。因为根本没有对 y
的地址进行赋值操作。在您的示例中, y
的地址没有变量(基本上是一个指针)(忘记分配)。
int* fun(int* x){
printf("Fun before %p - %d\n", x, *x);
x = malloc(sizeof(int));
*x = 20;
printf("Fun after %p - %d\n", x, *x);
return x; // return your new address
}
int main(){
int *y = malloc(sizeof(int));
*y = 31;
printf("Main before %p - %d\n", y, *y);
y = fun(y); // assign your new address here
printf("Main after %p - %d\n", y, *y);
return 0;
}
但上面的代码就可以了。
void fun(int* x){
x=(int*)malloc(sizeof(int));
*x = 20;
}
int main(){
int y=31;
fun(&y);
printf(%d,y);
}
为什么这段代码编译成功了?
评论:是在Eclipse上编译的 我在网上看到问题: x=(int*)malloc(sizeof(int));
为什么这个程序在运行时没有崩溃?
代码在语法上没有问题,因此可以编译。
y
的地址被传递给函数。函数中保存 y
地址的指针 x
被 malloc 分配的有效内存地址覆盖。一个 int 被写在那里而不是 y
因为指针的值被改变了。然后函数 returns(fun
中分配的内存执行 'leak')。
main中y
的值保持不变。
此程序的行为已定义。
嘿,你传递的是压入堆栈的变量 y 的地址副本。您只需通过分配 malloc
返回的地址并通过
*x = 20
这对 main
中的变量没有影响,即 y
如果你想让它打印 20 这可能会有所帮助
void fun(int** x){
*x=(int*)malloc(sizeof(int));
**x = 20;
}
int main(){
int *y;
fun(&y);
printf("%d",*y);
}
x=(int*)malloc(sizeof(int)); //x point to a new addr.
*x = 20; // change value of new pointer
删除行x=(int*)malloc(sizeof(int));
,就可以了。
我想你想做的是改变 main
函数中变量 y
的地址。您不能通过将 y
的地址值传递给函数来做到这一点。因为根本没有对 y
的地址进行赋值操作。在您的示例中, y
的地址没有变量(基本上是一个指针)(忘记分配)。
int* fun(int* x){
printf("Fun before %p - %d\n", x, *x);
x = malloc(sizeof(int));
*x = 20;
printf("Fun after %p - %d\n", x, *x);
return x; // return your new address
}
int main(){
int *y = malloc(sizeof(int));
*y = 31;
printf("Main before %p - %d\n", y, *y);
y = fun(y); // assign your new address here
printf("Main after %p - %d\n", y, *y);
return 0;
}
但上面的代码就可以了。