如何在C中创建用户定义的struct数组

我希望用户在程序启动时定义数组的大小,我目前有:

#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成为用户定义的值,所以在main函数中我有:

 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); 

array声明为指针并使用malloc动态分配所需的内存:

 struct ko* array; int SIZE; printf("enter array size"); scanf("%d", &SIZE); array = malloc(sizeof(struct ko) * SIZE); // don't forget to free memory at the end free(array); 

您可以使用malloc()库函数来使用动态内存分配:

 struct ko *array = malloc(SIZE * sizeof *array); 

请注意,对于变量使用ALL CAPS在C中是非常罕见的,因此在样式方面它非常混乱。

完成以这种方式分配的内存后,将指针传递给free()函数以取消分配内存:

 free(array); 

数组的大小是在编译时定义的,C不允许我们在运行时指定数组的大小。 这称为静态内存分配。 当我们处理的数据本质上是静态的时,这可能很有用。 但不能总是处理静态数据。 当我们必须存储本质上是动态的数据意味着数据大小在运行时发生变化时,静态内存分配可能是个问题。

要解决此问题,我们可以使用动态内存分配。 它允许我们在运行时定义大小。 它在请求大小和类型的匿名位置为我们分配一个内存块。 使用此内存块的唯一方法是使用指针。 malloc()函数用于动态内存分配,它返回一个指针,可用于访问分配的位置。

例-

假设我们处理整数类型值,整数的数量不固定,是动态的。

使用int类型数组来存储这些值将不会有效。

  int A[SIZE]; 

动态内存分配。

  int *A; A = (int*) malloc(SIZE * sizeof(int)); 

注意:类似的概念适用于struct。 成为分配的动态内存可以是任何类型。