我希望用户在程序启动时定义数组的大小,我目前有:
#define SIZE 10
typedef struct node{
int data;
struct node *next;
} node;
struct ko {
struct node *first;
struct node *last;
} ;
struct ko array[SIZE];
Run Code Online (Sandbox Code Playgroud)
这有效,但是,我想删除#define SIZE,并让SIZE成为用户定义的值,所以在主函数中我有:
int SIZE;
printf("enter array size");
scanf("%d", &SIZE);
Run Code Online (Sandbox Code Playgroud)
我该如何获得该数组的值?
编辑:现在我在.h文件中有以下内容:
typedef struct node{
int data;
struct node *next;
} node;
struct ko {
struct node *first;
struct node *last;
} ;
struct ko *array;
int size;
Run Code Online (Sandbox Code Playgroud)
这在main.c文件中:
printf("size of array: ");
scanf("%d", &size);
array = malloc(sizeof(struct ko) * size);
Run Code Online (Sandbox Code Playgroud)
这有用吗?这不是程序崩溃但我不知道问题是在这里还是在程序的其他地方......
而不是struct ko array[SIZE];动态分配它:
struct ko *array;
array = malloc(sizeof(struct ko) * SIZE);
Run Code Online (Sandbox Code Playgroud)
一旦完成,请务必释放它:
free(array);
Run Code Online (Sandbox Code Playgroud)