您好,我想声明一个大小为 x 的数组,这个大小将在运行时知道(不是静态声明)。怎么做。一种有效的方法。
我有这样的结构
#define SIZE 50
struct abc {
int students[SIZE];
int age;
}
我想在运行时从某个时间点读取 SIZE,而不是预先定义它。
编辑:我们能否为包括数组在内的整个结构动态分配内存。
strcut abc {
int *students; // should point to array of SIZE.
int age;
}s;
我们可以得到 sizeof struct = 整个结构的大小(包括数组)吗? ?
最佳答案
如果大小在运行时已知,则需要使用动态分配。
struct abc
{
int *students;
int age;
}
然后在代码中,
struct abc var;
var.students = malloc(size*sizeof(int));
在代码的末尾
free(var.students);
关于c - 在c中的结构内声明数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36082202/