c - 如何在 C 中创建用户定义的结构数组

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

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/

相关文章:

java - 伪代码数组符号混淆

c++ - 静态库与动态库

javascript - 如何动态更改单选按钮显示的信息?

将 char[2] 转换为 uint16_t 以进行套接字编程?

c - memset 空指针数组

c - 此 'realloc(): invalid next size' 错误的来源是什么

c - 按时间播种的随机数不会改变

arrays - 在 Ruby 中从数组创建固定长度的 FIFO

vb.net - 在数组中查找正方形

c - 在 C 中使用动态内存