在C语言中用变长数组初始化结构

在C语言中用变长数组初始化结构,c,struct,variable-length-array,C,Struct,Variable Length Array,有人知道有没有一种方法可以初始化包含可变长度数组的结构,而不必先在单独的变量中初始化数组(也不必使用malloc) 我的结构如下所示: struct my_struct { int *values; int size; } 现在,在我的代码中,我有: void my_function (int size) { int values[size]; struct my_struct mystr = { .values = values,

有人知道有没有一种方法可以初始化包含可变长度数组的结构,而不必先在单独的变量中初始化数组(也不必使用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;
这将不起作用,因为返回时
值的生存期将结束。如果您试图将
mystr
存储在函数参数所指向的值中,则同样适用

显然你没有这么做,但我认为无论如何都值得一提


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

你能确定
尺寸
小吗?否则堆栈将在
int值[size]
中溢出。它小而可预测吗?坚持你的第一个解决方案。如果它可能很大或依赖于用户输入,一定要使用
malloc

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

或者,您也可以使用,但无论如何,您必须
malloc
整个
mystr


还有一件事,你写道:

(首先初始化数组,然后初始化结构。这正在工作,但 为数组声明单独的变量看起来很尴尬。)


我不知道你的意思,但是
int*
只是
sizeof(intptr\u 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;
 }
#包括
结构测试{
整数计数;
int*值;
}测试[]={
#定义init(…){.count=sizeof((int[]){{uu-VA\u-ARGS\uu})/sizeof(int),.values=(int*)和(int[]){uu-VA\u-ARGS\uu}
初始值(0,1,2,3,4),
初始值(2,4,6,8),
init(1,3),
初始化(42)
};
#定义测试大小((int)(sizeof test/sizeof*test))
内部主(空)
{

对于(int-array=0;array)是否希望在不为数组分配空间的情况下使用数组?我知道我必须为数组分配空间,但我希望这样做时不使用中间变量,例如
int-values[size];
。`.values=calloc(size,sizeof(int))有什么问题,`?动态内存分配速度较慢,如果不小心,可能会导致内存泄漏。因此,除非绝对必要,否则我会尽量避免这种情况。因此,请使用NULL初始化
。值
,并在分配内存时放入实值
sizeof(int*)
不一定等于
sizeof(intptr\t)
。我认为你没有抓住重点;OP在这个问题上并不关心性能或内存使用。他/她希望更具表现力……这两个概念是正交的。