C 为什么我';我在函数中分配了指针内存,但它';它也是空的吗?
代码把我弄糊涂了C 为什么我';我在函数中分配了指针内存,但它';它也是空的吗?,c,C,代码把我弄糊涂了 #include <stdio.h> #include <stdlib.h> #include <assert.h> void create_int(int *p) { p = (int *) malloc(sizeof(int)); } int main() { int *p = NULL; create_int(p); assert(p != NULL); /* failed. why? I've
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
void create_int(int *p)
{
p = (int *) malloc(sizeof(int));
}
int main()
{
int *p = NULL;
create_int(p);
assert(p != NULL); /* failed. why? I've allocated memory for it. */
return 0;
}
#包括
#包括
#包括
void create_int(int*p)
{
p=(int*)malloc(sizeof(int));
}
int main()
{
int*p=NULL;
创建_int(p);
断言(p!=NULL);/*失败。为什么?我已经为它分配了内存*/
返回0;
}
您需要一个指向如下指针的指针:
void create_int(int **p)
{
*p = (int *) malloc(sizeof(int));
}
int main()
{
int *p = NULL;
create_int(&p);
assert(p != NULL); /* failed. why? I've allocated memory for it. */
return 0;
}
您没有从函数传回指针值。尝试:
void create_int(int **p) {
*p = (int *) malloc(sizeof(int));
}
int main() {
int *p = NULL;
create_int(&p);
assert(p != NULL); /* failed. why? I've allocated memory for it. */
return 0;
}
您需要向指针发送指针,以便能够通过函数为其分配内存
void create_int(int **p)
{
*p = (int*)malloc(sizeof_int));
}
int main()
{
int* p = NULL;
create_int(&p);
assert(p != NULL);
return 0;
}
函数
create_int
中的变量p
是main
中变量p
的副本。因此,对被调用函数中的p
所做的任何更改都不会反映在main
中
要使更改反映在main
中,您需要:
返回更改后的值:
int* create_int(int *p) {
p = malloc(sizeof(int));
// err checking
return p:
}
...
// in main:
p = create_int(p);
或者将p
的地址传递为:
void create_int(int **p) {
*p = malloc(sizeof(int));
// err checking
}
...
// in main:
create_int(&p);
正如人们指出的那样,它失败了,因为您没有实际更改调用方的指针 思考代码的另一种方式可能是注意到它基本上是包装
malloc()
,也就是说,它在进行内存分配,但添加了智能。在这种情况下,为什么不让它具有与malloc()
相同的原型(=调用签名)?这使得在调用方的上下文中更清楚发生了什么,并且更易于使用:
int * create_int(void)
{
return malloc(sizeof (int));
}
int main(void)
{
int *p = create_int();
assert(p != NULL);
return 0;
}
另外,在C语言中,您不应该强制转换malloc()的返回值(请参阅)。您的代码包含两个指针:一个在
create\u int
函数中,另一个在main
中。调用create_int
时,会制作并使用main
中指针的副本,然后在create_int
函数返回时消除
因此,您在create_int
中对副本所做的任何更改都将保留在那里,并且不会传播回main
在C中的函数之间传播更改的唯一方法(显然,除了返回新值之外)是传递一个指向更改值的指针。这样,当传递的指针将被复制时,它指向的值将是相同的,因此将应用更改
因为您试图更改指针,所以需要一个指向指针的指针
void create_int(int **pp)
{
// this changes the pointer that `p` points to.
*pp = (int *) malloc(sizeof(int));
}
int main()
{
int *p = NULL;
// this sends a pointer to the pointer p in main
create_int(&p);
assert(p != NULL);
return 0;
}
或者更好,
int*create_int(void){returnmalloc(sizeof(int))}
,然后只需int*p=create_int()
@HiMing:因为create_int
函数中的p
与main
函数中的p
是完全不同的变量。它最初只有相同的值,因为您在main中传递了一个值作为参数。在create_int
中更改p
的值对main
中的p
的值没有影响,该值仍然是一个空指针。此外,在C中,决不能强制转换malloc()的返回值。但我总是看到演员。为什么不投?@HiMing:我添加了相关链接,详情请参考该问题。sizeof(int*)
应该是sizeof(int)