[英]struct with a dynamic memory array element in c
我正在嘗試創建一個結構。 結構的元素之一是一個數組,如果需要,它應該能夠增長。
我這樣做:
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]);
}
但編譯器說:
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];
這工作正常:
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]);
}
順便說一句,我錯誤地忘記了刪除結構測試的聲明(現在沒有定義)並且編譯器沒有抱怨......)。 我還將感謝一個非常簡單(如果可能)的原因解釋。
1 - 我顯然不知道如何解決這個問題。
2 - 結構必須是指針嗎?
3 - 元素 arr 不能是指向 2darray 的指針嗎?
十分感謝!
免責聲明:我認為long int (*arr)[COLS]
(指向long
指針的靈活數組)是一個錯誤; 但您需要做的就是調整類型。
那看起來不太對勁。 如果 COLS 真的是動態的,我們需要說:
struct test{
long int (*arr)[];
};
但由於玩具示例太小,這是無效的。 彈性元素必須是最后一個,但也不能是唯一的。 需要看起來像這樣:
struct test{
size_t nelem; /* I suppose you could have another way of knowing how many */
long int (*arr)[];
};
然后你用一個看起來像這樣的調用來分配它:
struct test *ptr = malloc(sizeof(struct test) + sizeof (long int *) * COLS);
如果COLS
確實是常量,那么編譯的方法是將COLS
的聲明更改為宏,或者像這樣的enum
: enum { COLS = 2; };
enum { COLS = 2; };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.