将一个结构体嵌套到另一个结构体中使用的方法(C语言)

3

我在使用C语言中的struct时遇到了问题。
非常奇怪!!!
我无法在student结构体中使用course结构体。
虽然我之前已经定义过,但为什么会这样呢?

struct course
{
    int no;
    char name[30];
    int credits;
    float score;
};

struct student   
{
int no;
char name[50];
course c[3];
};

我的语言是c而不是c++


我的编程语言是C而不是C++。我敢打赌,如果你用的是C++,你就不会问这个问题了 :-) - Sergey Kalinichenko
6个回答

8

C++和C之间的一个区别在于,当使用C++类型时,可以省略类型关键字,如classstruct

问题出在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];


4

您需要在结构体名称前添加struct关键字:

struct course
{
    int no;
    char name[30];
    int credits;
    float score;
};

struct student   
{
    int no;
    char name[50];
    struct course c[3];
};

3
struct course c[3]; 

应该可以工作...


2
struct student {
    /* ... */
    struct course c[3];
}

或者

typedef struct _course {
    /* ... */
} course;

struct student {
    /* ... */
    course c[3];
}

1

你实际上可以定义一个匿名结构体然后给它取一个别名,例如:

typedef struct {
    /* stuff */
} course;

然后就像其他人说的那样,

struct student {
    course c[3];
}

0

typedef(类型定义)非常有用,因为它允许您缩短声明,这样您就不必总是输入单词struct

以下是一个涉及将结构体进行typedef的示例。它还在学生结构中包括了一个课程结构。

#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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接