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

如何在C中创建用户定义的struct数组,c,arrays,dynamic,C,Arrays,Dynamic,我希望用户在程序启动时定义阵列的大小,目前我有: #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成为用户定义的值,因此在主函数中我有:

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

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

数组
声明为指针,并使用以下各项动态分配所需内存:


您可以使用库函数使用动态内存分配:

struct ko *array = malloc(SIZE * sizeof *array);
请注意,在C语言中,对一个变量使用所有的大写字母是非常罕见的,从样式上看,这是相当混乱的

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

free(array);

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

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

范例-

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

使用int-type数组存储这些值将没有效率

  int A[SIZE];
动态内存分配

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

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

使用动态内存分配
malloc
您可以在C99中使用此语法。这里有一个链接:
(int)malloc()
应该是
(int*)malloc()
,而且它不是必需的,因为它是
void*
@user2408804我不确定您试图构建什么,所以很难说,但看起来您正在实现一个链接列表。内存分配部分在语法上看起来是正确的,但实际上没有链接列表,这会导致
first
last
中的指针无效,并且
struct ko
被分配
SIZE
次,而不是
struct节点
。我帮助您使用的代码是将
struct ko[10]
更改为
struct ko[SIZE]
的文字解决方案,但您的初始代码也是错误的。是的,它是一个链表数组,使用原始的静态数组分配,程序运行良好,但我似乎无法使其与动态分配一起工作。。无论如何,谢谢你的回复
  int *A;
  A = (int*) malloc(SIZE * sizeof(int));