我需要动态分配一个结构。我有一个带有这种类型的变量的结构:
int num;
char name[10];
float yep;
我需要输入一个数字i
,让我们假设i=4
。因此,我需要做的是输入num
,name
和yep
值的4倍,然后将它们保存到动态分配的数组中。我该如何实现?
答案 0 :(得分:0)
由于它被标记为c99,因此我根据您的要求考虑了添加到标准中的一些有趣的事情(编辑:可变长度数组-谢谢@underscore_d)。有一些要填写的内容,但这可能会让您入门。另一种方法是使用malloc从堆中获取结构的内存,而不是像我们下面所做的那样(有效地使用alloca)从堆栈中获取内存。 HTH:
#include <stdio.h>
typedef struct {
int num;
char name[10];
float yep;
} mystruct;
void do_something_with_n_structs(int n) {
mystruct structs[n];
int idx;
for (idx = 0; idx < n; ++idx) {
// fill this bit in
}
}
int main() {
int n = 0;
printf("Enter a number: "); fflush(stdout);
scanf("%d", &n);
do_something_with_n_structs(n);
return 0;
}