我希望用户在程序启动时定义数组的大小,我目前有:
#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
,让 SIZE 成为用户定义的值,所以在主函数中我有:
int SIZE;
printf("enter array size");
scanf("%d", &SIZE);
我怎样才能把这个值赋给数组?
编辑: 现在我在 .h 文件中有以下内容:
typedef struct node{
int data;
struct node *next;
} node;
struct ko {
struct node *first;
struct node *last;
} ;
struct ko *array;
int size;
在 main.c 文件中:
printf("size of array: ");
scanf("%d", &size);
array = malloc(sizeof(struct ko) * size);
这应该有效吗?它不会程序崩溃,但我不知道是不是问题 在这里或者,在程序的其他地方...
最佳答案
代替 struct ko array[SIZE];
,动态分配它:
struct ko *array;
array = malloc(sizeof(struct ko) * SIZE);
确保在完成后释放它:
free(array);
关于c - 如何在 C 中创建用户定义的结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16688372/