使用结构和函数时在C中初始化字符数组
我做了一个程序来理解结构的概念和从函数返回struct使用结构和函数时在C中初始化字符数组,c,function,struct,structure,C,Function,Struct,Structure,我做了一个程序来理解结构的概念和从函数返回struct struct student { char name[20]; int age; char subject[20]; int marks; int rollno; }sheet; struct student display() { sheet.name[20]="Swathi"; sheet.age=21; sheet.subject[20]="Mathematics";
struct student
{
char name[20];
int age;
char subject[20];
int marks;
int rollno;
}sheet;
struct student display()
{
sheet.name[20]="Swathi";
sheet.age=21;
sheet.subject[20]="Mathematics";
sheet.marks=85;
printf("Enter roll no.:");
scanf("%d",&sheet.rollno);
}
int main()
{
struct student sheet1;
sheet1=display();
printf("Name:%s",sheet.name);
printf("Age:%d",sheet.age);
}
我收到两条警告信息
warning: assignment makes integer from pointer without a cast [-Wint-conversion]
sheet.name[20]="Swathi";
warning: assignment makes integer from pointer without a cast [-Wint-conversion]
sheet.subject[20]="Mathematics";
为什么会这样?我应该如何改变这个 这里:
sheet.name[20]="Swathi";
只需获取Swathi的只读地址,隐式地将该地址强制转换为一个字符,使其无效,然后将其分配给sheet.name[20],这超出了范围,因此行为未定义。相反,请尝试以下方法:
strcpy(sheet.name, "Swathi");
同样,sheet.subject[20]=数学;。还要注意,struct student display没有返回任何内容,它应该是void display和struct student sheet1;不需要。它起作用了
struct student
{
char name[20];
int age;
char subject[20];
int marks;
int rollno;
}sheet;
struct student display()
{
strcpy(sheet.name, "Swathi");
sheet.age=21;
strcpy(sheet.subject,"Mathematics");
sheet.marks=85;
printf("Enter roll no.:");
scanf("%d",&sheet.rollno);
}
int main()
{
display();
printf("Name:%s",sheet.name);
printf("Age:%d",sheet.age);
}
不要再张贴这一常见的常见问题的答案了,请考虑近距离投票吧。可以在中找到合适的dupe目标列表。