#include <stdio.h>
#include <stdlib.h>
struct stud
{
int age;
struct stud *next;
};
typedef struct stud node;
node *createlist();
void main()
{
node *head;
head = createlist();
}
node *createlist()
{
node *head, *p;
head = (node *) malloc(sizeof(node));
int i, n;
printf("Enter the number of elements\n");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
if (i == 0)
{
p = head;
}
else
{
p->next = (node *) malloc(sizeof(node));
p = p->next;
}
p->age = i; /* This line here - what happens with (*p).age = i; or
&p->age = i; */
}
p->next = NULL;
return head;
}
Run Code Online (Sandbox Code Playgroud)
如果我将注释突出显示的代码替换为以下内容,有什么区别:
(*p).age = i;
Run Code Online (Sandbox Code Playgroud)
和
&p->age = i;
Run Code Online (Sandbox Code Playgroud)
基本上我正在创建一个结构stud的链接列表,我正在尝试将一些值初始化为它的成员.
您当前的代码是
p->age = i;
Run Code Online (Sandbox Code Playgroud)
那是完全相同的
(*p).age = i;
Run Code Online (Sandbox Code Playgroud)
另一方面,
&p->age = i;
Run Code Online (Sandbox Code Playgroud)
是一个编译错误.
因为->优先级高于&,所以解析为
&(p->age) = i;
Run Code Online (Sandbox Code Playgroud)
而且你不能分配int到的int*,更何况事实,&(p->age)不是左值.