菜鸡的疑惑。
我想用f()来给p完成内存分配与赋值,可是编译不通过,错误信息说‘data’不在星p里,
不太明白,故来提问。望指出错误。
代码如下:
#include
#include
struct node
{
char data;
};
void f(struct node** p);
int main() {
struct node* p;
f(&p);
printf("%c", p->data);
return 0;
}
void f(struct node** p)
{
p = (struct node)malloc(sizeof(struct node));
*p->data = 'D';
}
*p->data = 'D';
->
(*p)->data = 'D';
*p = (struct node*)malloc(sizeof(struct node));
(*p)->data = 'D';
指向指针的指针容易把人绕晕,这种情况可以使用指向指针的引用,这样不容易出错;void f(struct node*& p);
int main() {
struct node* p;
f(p);
printf("%c", p->data);
return 0;
}
```void f(struct node*& p)
{
p = (struct node*)malloc(sizeof(struct node));
p->data = 'D';
}