简体   繁体   English

将结构用于其他结构c

[英]use a struct into an other struct c

I have a problem using a struct in the C language. 我在使用C语言中的struct遇到问题。
It is very strange !!! 这很奇怪!!!
I cant use course struct in student struct. 我不能在student结构中使用course结构。
I have defined it before but ... why? 我以前定义过它但是......为什么?

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

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

My language is c not c++ 我的语言是C不是C ++

One of the differences between C++ and C is that you can omit type keywords such as class and struct when using C++ types. 一的C ++和C之间的差异是可以忽略类型关键字,如classstruct使用C ++类型时。

The problem is the line course c[3]; 问题是线路course c[3]; . In order to make it work, you have two choices--you can use a typedef on your struct course : 为了使它工作,你有两个选择 - 你可以在你的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;

or you can add the keyword struct in front of the broken line, ie struct course c[3]; 或者你可以在虚线前添加关键字struct ,即struct course c[3]; .

You need to prefix the struct name with the struct keyword: 您需要在struct name前面加上struct关键字:

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

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

应该管用...

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

or 要么

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

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

You should actually be able to define an anonymous struct and then typedef it, so: 您实际上应该能够定义一个匿名结构,然后键入它,所以:

typedef struct {
    /* stuff */
} course;

and then as the others have said, 然后正如其他人所说的,

struct student {
    course c[3];
}

typedefs are helpful, because they allow you to shorten declarations, so you are not always having to type the word struct . typedef很有用,因为它们允许你缩短声明,因此你不必总是输入单词struct

Here is an example involving typedef-ing your structs. 这是一个涉及对结构进行类型化的示例。 It also includes a course struct in the student 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM