在链表创建和输出中遇到的问题
#include <stdio.h>
#include <stdlib.h>
struct student
{
char name[20];
int num;
struct student *next;
};
int cnt;
struct student *create()
{
struct student *phead=NULL;
struct *pend,*pnew;
cnt=0;
pend=pnew=(struct student *)malloc(sizeof(struct student));
printf("please first enter name num:\n");
scanf("%s",pnew->name);
scanf("%d",&pnew->num);
while(pnew->num!=0)
{
cnt++;
if(cnt==1)
{
pnew->next=phead;
pend=pnew;
phead=pnew;
}
else
{
pnew->next=NULL;
pend->next=pnew;
pend=pnew;
}
pnew=(struct student*)malloc(sizeof(struct student));
scanf("%s",pnew->name);
scanf("%d",&pnew->num);
}
free(pnew);
return (phead);
}
void print(struct student *phead)
{
struct student *ptemp;
int n=1;
printf("********本名单中有%d个学生:********\n",cnt);
ptemp=phead;
while(ptemp!=NULL)
{
printf("第%d个学生是:\n",n);
printf("姓名:%s\n",ptemp->name);
printf("学号:%d\n",ptemp->num);
ptemp=ptemp->next;
n++;
}
}
int main(void)
{
struct student *phead;
phead=create();
print(phead);
return 0;
}
错误信息:
isual Studio\MyProjects\11\11.c(15) : warning C4133: '=' : incompatible types - from 'struct student *' to 'struct $S1 *'
D:\Program Files\Microsoft Visual Studio\MyProjects\11\11.c(17) : error C2037: left of 'name' specifies undefined struct/union '$S1'
D:\Program Files\Microsoft Visual Studio\MyProjects\11\11.c(18) : error C2037: left of 'num' specifies undefined struct/union '$S1'
D:\Program Files\Microsoft Visual Studio\MyProjects\11\11.c(19) : error C2037: left of 'num' specifies undefined struct/union '$S1'
D:\Program Files\Microsoft Visual Studio\MyProjects\11\11.c(24) : error C2037: left of 'next' specifies undefined struct/union '$S1'
D:\Program Files\Microsoft Visual Studio\MyProjects\11\11.c(26) : warning C4133: '=' : incompatible types - from 'struct $S1 *' to 'struct student *'
D:\Program Files\Microsoft Visual Studio\MyProjects\11\11.c(30) : error C2037: left of 'next' specifies undefined struct/union '$S1'
D:\Program Files\Microsoft Visual Studio\MyProjects\11\11.c(31) : error C2037: left of 'next' specifies undefined struct/union '$S1'
D:\Program Files\Microsoft Visual Studio\MyProjects\11\11.c(35) : warning C4133: '=' : incompatible types - from 'struct student *' to 'struct $S1 *'
D:\Program Files\Microsoft Visual Studio\MyProjects\11\11.c(36) : error C2037: left of 'name' specifies undefined struct/union '$S1'
D:\Program Files\Microsoft Visual Studio\MyProjects\11\11.c(37) : error C2037: left of 'num' specifies undefined struct/union '$S1'
总结问题:
错误信息提示 左边的 name 和 num 不是一个结构体 是因为在创建 create 的时候 有一个 struct *pnew,*pend出了问题 因为在定义结构体指针变量的时候 这种格式是错误的 应该是 struct 结构体名 *指针变量名 ,我刚才漏掉了结构体变量名 所以出现了问题。