Vas*_*asu 0 c struct data-structures
嗨,我想声明一个大小为x的数组,这个大小将在运行时知道(不是静态声明).怎么做.一种有效的方法.
我有这样的结构
#define SIZE 50
struct abc {
int students[SIZE];
int age;
}
Run Code Online (Sandbox Code Playgroud)
我想在运行时从某个点读取SIZE,而不是预先定义它.
编辑:我们可以动态地为整个结构(包括数组)分配内存.
strcut abc {
int *students; // should point to array of SIZE.
int age;
}s;
Run Code Online (Sandbox Code Playgroud)
我们可以得到sizeof struct =整个结构的大小(包括数组); ?
如果在运行时已知大小,则需要使用动态分配.
struct abc
{
int *students;
int age;
}
Run Code Online (Sandbox Code Playgroud)
然后在代码中,
struct abc var;
var.students = malloc(size*sizeof(int));
Run Code Online (Sandbox Code Playgroud)
在代码的最后
free(var.students);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
67 次 |
| 最近记录: |