简体   繁体   English

如何在C中的结构中存储可变长度数组

[英]How can I store a variable length array in a struct in C

I want to store a variable length array in a struct, and I use a pointer for this purpose. 我想在结构中存储一个可变长度的数组,为此我使用了一个指针。 However, if I retrieve the stored array, I get the wrong values back. 但是,如果检索存储的数组,则会返回错误的值。 In the example below, I get the output "1 0", while you would expect the output "1 2". 在下面的示例中,我得到输出“ 1 0”,而您期望输出“ 1 2”。

#include <stdio.h>

typedef struct Flexibility {
    int *flex;
} Flexibility;

Flexibility calculateFlexibility()
{
    int a[2];
    a[0] = 1;
    a[1] = 2;

    Flexibility f;
    f.flex = a;
    return f;
}


void main()
{
    Flexibility f;
    f = calculateFlexibility();

    int i;
    for(i = 0; i < 2; i++)
    {
        fprintf(stdout, "%i ", *(f.flex + i));
    }

}

you're creating temporary variable a in function calculateFlexibility , then you store pointer to f.flex variable, but after function is ended - a is gone from memory, so your f.flex pointer is now pointing to nowhere 要创建临时变量a函数calculateFlexibility ,那么你存储指针f.flex变量,但功能结束之后- a是从内存中消失了,所以你f.flex指针正指向无处

if you want to have really variable length, you should do something like this: 如果您想要真正可变的长度,则应执行以下操作:

Flexibility calculateFlexibility()
{
    Flexibility f;
    f.flex = (int*)malloc(....);
    return f;
}

and at the end of program: 并在程序结束时:

free(f.flex);

for proper arguments of malloc I suggest you to read: http://en.cppreference.com/w/c/memory/malloc 有关malloc的正确参数,建议您阅读: http : //en.cppreference.com/w/c/memory/malloc

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

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