2012-06-22 105 views
3

我在C語言中使用struct時出現問題。
這很奇怪!
我無法使用course結構在student結構。
我已經定義過,但是... 爲什麼?在另一個結構中使用一個結構c

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

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

我的語言Ç沒有C++

+0

「我的語言是C不是C++」我敢打賭,如果它是C++,你就不會問這個問題:-) – dasblinkenlight

+0

這是功課? – octopusgrabbus

回答

3
struct course c[3]; 

應該工作...

+0

你的意思是struct course {.....} typedef; – user1472850

4

您需要用struct關鍵字的前綴結構名稱:

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

struct student 
{ 
    int no; 
    char name[50]; 
    struct course c[3]; 
}; 
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,即structcourse 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

typedefs有幫助,因爲becau他們允許你縮短聲明,所以你不一定要輸入單詞struct

下面是一個涉及typedef-ing結構的例子。它還包含學生結構中的課程結構。

#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; 
} 
相關問題