您可能希望将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