[英]use a struct into an other struct c
我在使用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之間的差異是可以忽略類型關鍵字,如class
和struct
使用C ++類型時。
問題是線路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];
。
您需要在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];
}
要么
typedef struct _course {
/* ... */
} course;
struct student {
/* ... */
course c[3];
}
您實際上應該能夠定義一個匿名結構,然后鍵入它,所以:
typedef struct {
/* stuff */
} course;
然后正如其他人所說的,
struct student {
course c[3];
}
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.