您可能希望將id
字段添加到您的Student
數據結構,例如:
typedef struct {
int id;
int age;
int phoneNumber;
} Student;
然後,你可以定義一個具有固定標題的結構(在這種情況下,這可以是nu學生MBER),隨後的Student
秒的可變大小的數組:
#define ARRAY_OF_ANY_SIZE 1
typedef struct {
int count;
Student students[ARRAY_OF_ANY_SIZE];
} People;
This blog post解釋具有「尺寸1的陣列」,包括對準問題的討論的這種技術。
我不會在這裏重複原始的博客帖子代碼。請考慮您可以使用便攜式offsetof()
而不是Windows特定的FIELD_OFFSET()
宏。
作爲示例代碼,你可能要考慮以下幾點:
#include <stdio.h> /* For printf() */
#include <stddef.h> /* For offsetof() */
#include <stdlib.h> /* For dynamic memory allocation */
typedef struct {
int id;
int age;
int phoneNumber;
} Student;
#define ARRAY_OF_ANY_SIZE 1
typedef struct {
int count;
Student students[ARRAY_OF_ANY_SIZE];
} People;
int main(int argc, char* argv[]) {
People* people;
const int numberOfStudents = 3;
int i;
/* Dynamically allocate memory to store the data structure */
people = malloc(offsetof(People, students[numberOfStudents]));
/* Check memory allocation ... */
/* Fill the data structure */
people->count = numberOfStudents;
for (i = 0; i < numberOfStudents; i++) {
people->students[i].id = i;
people->students[i].age = (i+1)*10;
people->students[i].phoneNumber = 11000 + i;
}
/* Print the data structure content */
for (i = 0; i < people->count; i++) {
printf("id: %d, age=%d, phone=%d\n",
people->students[i].id,
people->students[i].age,
people->students[i].phoneNumber);
}
/* Release the memory allocated by the data structure */
free(people);
return 0;
}
輸出:
id: 0, age=10, phone=11000
id: 1, age=20, phone=11001
id: 2, age=30, phone=11002
[這個答案](http://stackoverflow.com/questions/20221012/unsized-array-declaration-in-a-struct/20221073#20221073)是我使用靈活數組成員的一個很好的例子。 –
爲什麼不在'People'中有一個'Student'數組? – Brian
好吧,結構不能改變 – ratzip