#include<stdio.h>
struct names
{
char name1[49];
char name2[48];
char name3[49];
};
stud1,stud2,stud3;
int main()
{
char names;
printf("enter first name of the first studentn");
scanf("%s",&struct names.name1.stud1);
printf("enter second name of the first studentn");
scanf("%s",&struct names.name2.stud1);
printf("enter third name of the first studentn");
scanf("%s",&struct names.name3.stud1);
printf("enter first name of the second studentn");
scanf("%s",&struct names.name1.stud2);
printf("enter second name of the second studentn");
scanf("%s",&struct names.name2.stud2);
printf("enter third name of the second studentn");
scanf("%s",&struct names.name3.stud2);
printf("enter first name of the third studentn");
scanf("%s",&struct names.name1.stud3);
printf("enter second name of the third studentn");
scanf("%s",&struct names.name2.stud3);
printf("enter third name of the third studentn");
scanf("%s",&struct names.name3.stud3);
return 0;
}
你的结构定义看起来不错,但是这个:
stud1,stud2,stud3;
将声明三个整数变量。它不会在较新的标准(如 C99)下编译。您需要三个类型为 struct names
的变量:
struct names stud1, stud2, stud3;
使用变量时:
scanf("%s",&struct names.name1.stud1);
您不使用 struct names
,这是变量 stud1
的类型。仅当您对变量进行递减时,才使用它,以便编译器知道它是什么类型。之后,使用其名称。此外,结构变量 bname 排在第一位,字段名称排在第二位。而且 fiels name1
是一个字符数组,所以你不应该取它的地址。最后,最好向scanf
发出信号,不要使阵列溢出。所以:
scanf("%48s", &stud1.name1);
请再次阅读 C 入门中有关类型和变量的章节。
附录:可以一次性定义结构和变量,正如其他人所建议的那样:
struct names {
char name1[49];
char name2[48];
char name3[49];
} stud1, stud2, stud3;
我发现这样的化合物定义比有用更令人困惑。我建议作为初学者,您应该坚持结构和变量定义的分离。
您可以通过删除代码中结构体后面的 seimcolon 来获取此定义,但它不会修复您使用结构体的 systax。
试试看:
#include
struct names
{
char name1[49];
char name2[48];
char name3[49];
}stud1,stud2,stud3;
int main()
{
printf("enter first name of the first studentn");
scanf("%s",&stud1.name1);
printf("enter second name of the first studentn");
scanf("%s",&stud1.name2);
printf("enter third name of the first studentn");
scanf("%s",&stud1.name3);
printf("enter first name of the second studentn");
scanf("%s",&stud1.name1);
printf("enter second name of the second studentn");
scanf("%s",&stud2.name2);
printf("enter third name of the second studentn");
scanf("%s",&stud2.name3);
printf("enter first name of the third studentn");
scanf("%s",&stud3.name1);
printf("enter second name of the third studentn");
scanf("%s",&stud3.name2);
printf("enter third name of the third studentn");
scanf("%s",&stud3.name3);
return 0;
}