[英]Accessing and assigning values in each part of the struct in an “array” of structs?
[英]Accessing an array element inside a struct (which is part of an array of structs) (in C)
我想創建一個結構數組,盡管沒有。 從文件中讀取數組中的結構/從用戶輸入。
我聲明一個結構:
struct student{
char name[16];
int *available;
int sum;
};
typedef struct student ST;
我為結構數組分配內存(獲取大小的輸入后):
ptr = (ST*)calloc(lines, sizeof(ST));
我還為每個結構中的每個數組分配空間(使用循環):
ptr->available = (int*)calloc(lines, sizeof(int));
現在-我想將值放入這些數組中。 如何達到每個要素?
我試過了:
*((ptr+i)->(available+j)) = 1;
但是編譯器告訴我: error: expected identifier before '('
(i和j是我使用的索引,i表示第i個結構,j表示數組的第j個元素)。
我究竟做錯了什么?
考慮使用數組索引符號以提高可讀性:
ptr[i].available[j] = 1;
(使用顯式指針算法的等效語法是*((ptr + i)->available + j) = 1;
)。
忘記*(ptr + idx)
表示法; 它被用來使初學者感到困惑,而不是在“真實代碼”中。 但是,如果必須使用它,則:
*((ptr+i)->available+j) = 1;
但是使用:
ptr[i].available[j] = 1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.