2015-09-21 46 views
4

爲A結構類型定義:分配值,以結構變量

typedef struct student{ 
    int id; 
    char* name; 
    double score; 
} Student; 

我構造類型學生的變量,我想值分配給它。我該如何有效地做到這一點?

int main(){ 

Student s1; 

int id = 3; 

char* name = getName(id); 

double score = getScore(id); 

/*Error 
s1 = {id, name, score}; 
*/ 

/* Can I avoid assigning values individually? 
s1->id = id; 
s1->name = name; 
s1->score= score; 
*/ 

return 0; 
} 
+2

除非我不明白的問題,這是應該由自己通過簡單的學習有什麼C的結構,以及如何使用它們來回答一個「C基本的學習」的問題。但是你正在談論使用唯一ID訪問結構實例。那麼你也應該看看那個「C指針」是什麼。 –

回答

2

我能避免單獨把值?

你可以,如果值已經有類似struct部分,即,你可以這樣做:

Student s1 = {.id = id, .name = name, .score = score}; 

這就造成Student一個實例並初始化您指定的字段。這可能並不比單獨賦值更高效,但它確實保持了代碼的簡潔。一旦你有一個現有的Student例如,您可以用簡單的賦值複製:

Student s2; 
s2 = s1; // copies the contents of s1 into s2 

如果這些值都在獨立的變量,你不初始化Student,那麼你可能需要分配值分別。你總是可以寫,做,對你,雖然一個功能,讓你有這樣的:

setupStudent(s3, id, name, score); 

,留住你的代碼的短,確保結構填充每次都以同樣的方式,並簡化你的生活當(不是如果)Student的定義改變。

7

要小心,struct和struct指針是兩個不同的東西。

Ç爲您提供:

  • 結構初始化(僅在聲明時):

    struct Student s1 = {1, "foo", 2.0 }, s2; 
    
  • 結構副本:

    struct Student s1 = {1, "foo", 2.0 }, s2; 
    s2 = s1; 
    
  • 直接元素訪問:

    struct Student s1 ; 
    s1.id = 3; 
    s1.name = "bar"; 
    s1.score = 3.0; 
    
  • 操縱通過指針:

    struct Student s1 = {1, "foo", 2.0 }, s2, *ps3; 
    ps3 = &s2; 
    ps3->id = 3; 
    ps3->name = "bar"; 
    ps3->score = 3.0; 
    
  • 初始化函數:那些其中

    void initStudent(struct Student *st, int id, char *name, double score) { 
        st->id = id; 
        st->name = name; 
        st->score = score; 
    } 
    ... 
    int main() { 
        ... 
        struct Student s1; 
        iniStudent(&s1, 1, "foo", 2.0); 
        ... 
    } 
    

皮克(或其它尊重C標準),但s1 = {id, name, score};不過是一個語法錯誤;-)

15

在C99標準中,您可以指定val使用複合文字的UE:

Student s1; 
s1 = (Student){.id = id, .name = name, .score = score}; 
+8

我不能相信沒有人給出這個答案,直到2017年5月10日。 –