c - 在c中的结构内声明数组

标签 c data-structures struct

您好,我想声明一个大小为 x 的数组,这个大小将在运行时知道(不是静态声明)。怎么做。一种有效的方法。

我有这样的结构

    #define SIZE 50
    struct abc {
                  int students[SIZE];
                  int age;
   }

我想在运行时从某个时间点读取 SIZE,而不是预先定义它。

编辑:我们能否为包括数组在内的整个结构动态分配内存。

        strcut abc {
                     int *students; // should point to array of SIZE.
                     int age;
       }s;

我们可以得到 sizeof struct = 整个结构的大小(包括数组)吗? ?

最佳答案

如果大小在运行时已知,则需要使用动态分配。

struct abc 
{
  int *students;
  int age;
}

然后在代码中,

struct abc var;
var.students = malloc(size*sizeof(int));

在代码的末尾

free(var.students);

关于c - 在c中的结构内声明数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36082202/

相关文章:

将 int 函数转换为 void*

c - c 中的翻译器和预处理器相同吗?

language-agnostic - C#数据结构算法

c - 为什么这样的结构体包含两个仅包含一个元素的数组字段?

json - 将 JSON 文件解析为 struct golang

编译器跳过循环

c++ - gettimeofday() - 为什么同时使用秒和微秒?

c - 如何用kmalloc进行数据结构对齐?

algorithm - 修改heapsort算法,一次从堆中取出k个元素

c - 我无法弄清楚我的指针错误