繁体   English   中英

在C中使用可变长度数组初始化结构

[英]Initializing structure with variable length array in C

有谁知道是否有一种方法可以初始化包含可变长度数组的结构,而无需先在单独的变量中初始化数组(并且无需使用malloc)?

我的结构如下所示:

struct my_struct {
    int *values;
    int size;
}

现在在我的代码中,我有:

void my_function (int size) {
    int values[size];
    struct my_struct mystr = {
        .values = values,
        .size = size
    };
    ...
}

(先初始化数组,然后初始化结构。这是可行的,但为数组声明一个单独的变量看起来很尴尬。)

这可能也可以工作:

void my_function (int size) {
    struct my_struct mystr = { 
        .values = calloc (size, sizeof (int)),
        .size = size
    };
    ...
}

(但我不想使用mallocs)

但是我想写的是这样的:

void my_function (int size) {
    struct my_struct mystr = { 
        .values = (int[size]){},
        .size = size
    };
    ...
}

任何想法?

首先,请注意,如果要返回结构,则不能使用堆栈中的数组。

int values[size];
struct my_struct mystr = {
    .values = values,
    .size = size
};
return mystr;

这将无法正常工作,因为返回values的生命周期将结束。 如果尝试将mystr存储在函数的参数所指向的值中,则同样适用。

显然您并没有这样做,但是无论如何我还是值得一提。


回答您的问题:这取决于情况。

您可以确定size很小吗? 否则您的堆栈将在int values[size]溢出。 它很小并且可以预测吗? 坚持第一个解决方案。 如果它可以很大或取决于用户输入,请绝对使用malloc

您是以某种方式返回或保留指向您的结构或值的持久指针吗? 使用malloc (请参阅我的第一句话)。

另外,您也可以使用结构黑客但你必须malloc整个mystr反正。


您还写了另一件事:

(先初始化数组,然后初始化结构。这是可行的,但为数组声明一个单独的变量看起来很尴尬。)

我不确定您的意思,但是int *仅为sizeof(intptr_t) ,与数组的大小无关。 因此,如果您要这样做,就不会为1个数组分配两倍的内存。

初始化程序是由初始化程序列表初始化的未命名对象。 在函数主体之外,对象具有静态存储持续时间。 因此可以使用此类对象的地址。 在可变参数宏的一点帮助下,您可以尝试→

 #include <stdio.h>

 struct test {
   int count;
   int *values;
 } test[] = {
 #define init(...) { .count=sizeof( (int[]) {__VA_ARGS__} )/sizeof(int), .values=(int *)&(int []){__VA_ARGS__} }
              init(0,1,2,3,4),
              init(2,4,6,8),
              init(1,3),
              init(42)
            };
 #define test_size ((int) (sizeof test/sizeof *test))

 int main(void)
 {
   for(int array=0; array<test_size; ++array) {
     printf("array %d (%d) : [ ", array+1, test[array].count);
     for(int i=0; i<test[array].count; ++i)
       printf("%d ", test[array].values[i]);
     puts("]");
   }
   return 0;
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM