简体   繁体   English

在 c 中具有动态 memory 数组元素的结构

[英]struct with a dynamic memory array element in c

I am trying to create a struct.我正在尝试创建一个结构。 One of the elements of the struct is an array that should be able to grow if needed.结构的元素之一是一个数组,如果需要,它应该能够增长。

I do this:我这样做:

int  COLS=2, ROWS=20;
long int (*array)[COLS] = malloc(sizeof(int[ROWS][COLS]));

struct test{
    long int (*arr)[COLS];
};

struct test *s_test = malloc(sizeof(s_test));
s_test->arr = array;

for (int i=0; i<ROWS; i++){
    array[i][0]=i;
    array[i][1]=i+20;

    printf("0:%ld\t1:%ld\n",s_test->arr[i][0], s_test->arr[i][1]);
}

but the compiler says:但编译器说:

test.c:10:14: error: fields must have a constant size: 'variable length array in structure' extension will never be supported
                long int (*arr)[COLS];

This works ok:这工作正常:

int COLS=2, ROWS=20;
long int (*array)[COLS] = malloc(sizeof(int[ROWS][COLS]));

long int (*arr)[COLS];

//struct test{
//  long int (*arr)[COLS];
//};

struct test *s_test = malloc(sizeof(s_test));

//s_test->arr = array;

arr = array;

for (int i=0; i<ROWS; i++){
    array[i][0]=i;
    array[i][1]=i+20;

    printf("0:%ld\t1:%ld\n", arr[i][0], arr[i][1]); //s_test->arr[i][0], s_test->arr[i][1]);
}

BTW, I, mistakenly forgot to delete the declaration of a struct test (which is not defined now) and the compiler didn't complain...).顺便说一句,我错误地忘记了删除结构测试的声明(现在没有定义)并且编译器没有抱怨......)。 I will also appreciate a very simple (if possible) explanation of why.我还将感谢一个非常简单(如果可能)的原因解释。

1 - I clearly don't know how to solve this problem. 1 - 我显然不知道如何解决这个问题。
2 - Does the struct HAS to be a pointer? 2 - 结构必须是指针吗?
3 - Can't the element arr be a pointer to theh 2darray? 3 - 元素 arr 不能是指向 2darray 的指针吗?

Thank you a lot!十分感谢!

Disclaimer: I think long int (*arr)[COLS] (flexible array to pointer to long ) is a mistake;免责声明:我认为long int (*arr)[COLS] (指向long指针的灵活数组)是一个错误; but all you need to do to fix it is adjust the type.但您需要做的就是调整类型。

That doesn't look quite right.那看起来不太对劲。 if COLS really is dynamic we need to say:如果 COLS 真的是动态的,我们需要说:

struct test{
    long int (*arr)[];
};

but this is invalid due to the toy example being too small.但由于玩具示例太小,这是无效的。 The stretchy element has to be the last one, but it can't be the only one either.弹性元素必须是最后一个,但也不能是唯一的。 Needs to look like this:需要看起来像这样:

struct test{
    size_t nelem; /* I suppose you could have another way of knowing how many */
    long int (*arr)[];
};

and you allocate it with a call that looks like this:然后你用一个看起来像这样的调用来分配它:

    struct test *ptr = malloc(sizeof(struct test) + sizeof (long int *) * COLS);

If COLS is really constant, the way to get to compile is to change the declaration of COLS to be a macro, or an enum like so: enum { COLS = 2; };如果COLS确实是常量,那么编译的方法是将COLS的声明更改为宏,或者像这样的enumenum { COLS = 2; }; enum { COLS = 2; };

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

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