2017-01-16 97 views
0

我有這樣的:如何在C中訪問數組中的特定結構?

typedef struct{ 
    field_1; 
    field 2; 
    ..... 
}student; 

typedef struct{ 
    student record[100]; 
    int counter; 
}List; 

然後我想添加每個「學生」的信息,例如:

List *p; 
gets(p->list[index]->field_1); 

但是當我編譯它拋出此代碼:

[Error] base operand of '->' has non-pointer type 'student' 

那麼爲什麼我不能指向'列表'和訪問'列表'中特定「記錄」的方式?

+2

使用'.'操作者而不是' - >'(第二個).. –

+0

或者complentarty創建指針學生的陣列。 – hetepeperfan

回答

1

添加代碼片段,可以幫助你讀/值寫入的記錄。 完成後釋放指向結構體的指針。

typedef struct{ 
int age; 
int marks; 
}student; 

typedef struct{ 
student record[100]; 
int counter; 
}List; 

int main() 
{ 
    List *p = (List*)malloc(sizeof(List)); 

    p->record[0].age = 15; 
    p->record[0].marks = 50; 
    p->counter = 1; 
    free(p); 
    return 0; 
} 
+0

不錯。我在詢問使用'malloc()'函數。但是會調用'sizeof(List)'創建未使用的'counter'變量嗎? –

+0

不,它不會。它只會爲計數器變量分配4個字節的內存。 – user7375520

1

列表本身p是一個指針,但值record[100]不是。您可以使用->運算符訪問p,然後訪問.運算符的值,以訪問成員records的值。

+0

然後我可以使用malloc()函數而不是給定固定數量的記錄嗎?會有什麼問題嗎? –

1

當你寫

`p->record[index]->field_1` 

其展開 (*p).(*record[index]).field_1

record[index]` 

所以在之前,添加*操作沒有意義本身返回值。但是你可以使用

p->(record+index)->field_1