我在 C 语言中使用struct
时遇到问题。
这很奇怪!!!
我无法在course
结构中使用student
结构。
我以前定义过它但是......
为什么呢?
struct course
{
int no;
char name[30];
int credits;
float score;
};
struct student
{
int no;
char name[50];
course c[3];
};
我的语言 c 而非 c ++
答案 0 :(得分:8)
C ++和C之间的区别之一是,在使用C ++类型时,您可以省略类型关键字,例如class
和struct
。
问题是行course c[3];
。为了使其有效,您有两种选择 - 您可以在struct course
上使用typedef:
typedef struct _course // added an _ here; or we could omit _course entirely.
{
int no;
char name[30];
int credits;
float score;
} course;
或者您可以在虚线前添加关键字struct
,即 struct
course c[3];
。
答案 1 :(得分:4)
您需要在结构名称前加上struct
关键字:
struct course
{
int no;
char name[30];
int credits;
float score;
};
struct student
{
int no;
char name[50];
struct course c[3];
};
答案 2 :(得分:3)
struct course c[3];
应该有用......
答案 3 :(得分:2)
struct student {
/* ... */
struct course c[3];
}
或
typedef struct _course {
/* ... */
} course;
struct student {
/* ... */
course c[3];
}
答案 4 :(得分:1)
您实际上应该能够定义一个匿名结构,然后键入它,所以:
typedef struct {
/* stuff */
} course;
然后正如其他人所说的那样,
struct student {
course c[3];
}
答案 5 :(得分:0)
typedef很有用,因为它们允许您缩短声明,因此您不必总是键入单词struct
。
这是一个涉及对结构进行类型化的示例。它还包括学生结构中的课程结构。
#include <stdio.h>
#include <string.h>
typedef struct course_s
{
int no;
char name[30];
int credits;
float score;
} course;
typedef struct student_s
{
int no;
char name[50];
course c[3];
} student;
bool isNonZero(const int x);
int main(int argc, char *argv[])
{
int rc = 0;
student my_student;
my_student.c[0].no = 1;
return rc;
}