如何使结构体在C用户定义的数组 [英] How to make a user defined array of struct in C
问题描述
我想用户定义数组的大小在程序启动时,我目前有:
I would like the user to define the size of the array when the program starts, I currently have:
#define SIZE 10
typedef struct node{
int data;
struct node *next;
} node;
struct ko {
struct node *first;
struct node *last;
} ;
struct ko array[SIZE];
这不过的工作,我想删除的#define SIZE
,让大小是用户定义的值,所以在主函数中我有:
This works, however, I would like to remove the #define SIZE
, and let SIZE be a value that the user defines, so in the main function i have:
int SIZE;
printf("enter array size");
scanf("%d", &SIZE);
我怎么可以得到价值的阵列?
how can I get that value to the array?
编辑:
现在我已经中.h文件中以下内容:
now i have the following in the .h file:
typedef struct node{
int data;
struct node *next;
} node;
struct ko {
struct node *first;
struct node *last;
} ;
struct ko *array;
int size;
和这main.c文件:
and this in the main.c file:
printf("size of array: ");
scanf("%d", &size);
array = malloc(sizeof(struct ko) * size);
如若这项工作?它没有程序崩溃,但我不知道,如果问题
在这里,或者其他地方的计划...
Should this work? It doesn't the program crashes but I don't know if the problem is here or, elsewhere in the program...
推荐答案
而不是结构こ阵列[SIZE];
,动态分配的:
struct ko *array;
array = malloc(sizeof(struct ko) * SIZE);
确认释放它,一旦你用它做:
Make sure to free it once you're done with it :
free(array);
这篇关于如何使结构体在C用户定义的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!