我试图在C中实现一个结构,我得到了这些错误。
请帮助我解决这个错误,并向我解释我做错了什么。
main.c:7:12: error: variable ‘s1’ has initializer but incomplete type
7 | struct student s1 = {"Nick",16,50,72.5};
| ^~~~~~~
main.c:7:26: warning: excess elements in struct initializer
7 | struct student s1 = {"Nick",16,50,72.5};
| ^~~~~~
main.c:7:26: note: (near initialization for ‘s1’)
main.c:7:33: warning: excess elements in struct initializer
7 | struct student s1 = {"Nick",16,50,72.5};
| ^~
main.c:7:33: note: (near initialization for ‘s1’)
main.c:7:36: warning: excess elements in struct initializer
7 | struct student s1 = {"Nick",16,50,72.5};
| ^~
main.c:7:36: note: (near initialization for ‘s1’)
main.c:7:39: warning: excess elements in struct initializer
7 | struct student s1 = {"Nick",16,50,72.5};
| ^~~~
main.c:7:39: note: (near initialization for ‘s1’)
main.c:7:20: error: storage size of ‘s1’ isn’t known
7 | struct student s1 = {"Nick",16,50,72.5};
我的代码
#include<stdio.h>
#include<stdlib.h>
int main()
{
struct student s1 = {"Nick",16,50,72.5};
printf("%s",s1.name);
// return 0;
}
struct student{
char name[4];
int age;
int roll_no;
float marks;
}s1;
发布于 2021-11-26 17:48:04
在本声明的要点上
struct student s1 = {"Nick",16,50,72.5};
编译器不知道结构是如何定义的,它有哪些数据成员。所以它会发出信息。
您需要在声明结构类型的对象之前放置结构定义。例如
struct student{
char name[4];
int age;
int roll_no;
float marks;
};
int main( void )
{
struct student s1 = {"Nick",16,50,72.5};
//...
注意,您正在尝试声明两个名称为s1的结构类型的对象。
第一个主要声明为
struct student s1 = {"Nick",16,50,72.5};
和第二个文件范围后的main
struct student{
char name[4];
int age;
int roll_no;
float marks;
}s1;
删除文件范围中的此声明,并将结构定义放在main之前,如上面所示。
发布于 2021-11-26 17:46:45
C编译器从上到下读取每个源文件。因此,当您尝试创建一个类型为struct student
的变量时,还没有定义该类型。
在使用结构定义之前,将其移动到文件的顶部。
发布于 2021-11-26 19:14:15
如评论中所示,您的代码有几个问题:
当您尝试使用compiler
char[4]
时,0
.
还不知道struct
太短,无法容纳"Nick“,因为每个字符串中都有一个终止NULL
,为了在printf()
中使用name
和%s
,您需要这个终止NULL
我将向您展示一个示例,并给出几种常用的声明和使用方法
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
char name[15];
int age;
int roll_no;
float marks;
} Student;
int main()
{
Student one;
Student other = {"Nick", 16, 50, 72.5};
Student modern_way =
{
.age = 12,
.name = "James Bond 007"
};
one = other; // one had no value yet
Student a_group[3] =
{
[1] = one,
[0] = other,
[2] = modern_way
};
printf("%s, %d\n%s, %d\n",
one.name, one.age,
other.name, other.age
);
printf("%s, %d\n", modern_way.name, modern_way.age);
// now a loop to list the ones in the array
for (int i = 0; i < 3; i += 1)
printf("%2d: %s, %d\n",
i,
a_group[i].name,
a_group[i].age);
return 0;
}
输出
Nick, 16
Nick, 16
James Bond 007, 12
0: Nick, 16
1: Nick, 16
2: James Bond 007, 12
在代码中可以看到,创建typedef
Student
要方便得多,这样您就可以使用它,而不必在整个代码中记住和重新键入struct
。
同样有用的是使用大写大写的第一个字母作为命名事物的惯例。
one
是声明的,但没有初始化,但是在代码的后面分配了一个值。
modern_way
是以NotNew90的方式初始化的,您可以按任何顺序命名字段,只初始化需要的字段。
a_group
向您展示了如何处理初始化数组的方法,并显示您甚至可以在代码中使用其他已知值。
一个for
循环展示了如何将它们全部列出。
https://stackoverflow.com/questions/70128209
复制相似问题