我想在结构中包含一个可变长度数组,但是在正确初始化它时遇到了问题.
struct Grid {
int rows;
int cols;
int grid[];
}
int main() {
struct Grid testgrid = {1, 3, {4, 5, 6}};
}
Run Code Online (Sandbox Code Playgroud)
我尝试的一切都给了我一个'错误:灵活数组成员的非静态初始化'错误.
sam*_*wry 27
这是我的版本:
#include <stdio.h>
struct matrix {
int rows;
int cols;
int **val;
} a = { .rows=3, .cols=1,
.val = (int*[3]){ (int[1]){1},
(int[1]){2},
(int[1]){3} } },
b = { .rows=3, .cols=4,
.val = (int*[3]){ (int[4]){1, 2, 3, 4},
(int[4]){5, 6, 7, 8},
(int[4]){9,10,11,12} } };
void print_matrix( char *name, struct matrix *m ){
for( int row=0;row<m->rows;row++ )
for( int col=0;col<m->cols;col++ )
printf( "%s[%i][%i]: %i\n", name, row, col, m->val[row][col] );
puts("");
}
int main(){
print_matrix( "a", &a );
print_matrix( "b", &b );
}
Run Code Online (Sandbox Code Playgroud)
Dig*_*oss 12
您可以通过将结构设置为static全局或全局来使其在gcc中工作,但事实证明初始化灵活的数组成员是不符合的,因此除了使用gcc之外它可能不起作用.这是一种只使用符合C99标准的功能的方法......
#include <stdlib.h>
#include <stdarg.h>
typedef struct Grid {
int rows;
int cols;
int grid[];
} *Grid;
Grid newGrid(int, int, ...);
Grid newGrid(int rows, int cols, ...)
{
Grid g;
va_list ap;
int i, n = rows * cols;
if((g = malloc(sizeof(struct Grid) + rows * cols * sizeof(int))) == NULL)
return NULL;
g->rows = rows;
g->cols = cols;
va_start(ap, cols);
for(i = 0; i < n; ++i)
g->grid[i] = va_arg(ap, int);
va_end(ap);
return g;
}
.
.
.
Grid g1, g2, g3;
g1 = newGrid(1, 1, 123);
g2 = newGrid(2, 3, 1, 1, 1,
2, 2, 2);
g3 = newGrid(4, 5, 1, 2, 3, 4, 5,
6, 7, 8, 9, 10,
11, 12, 13, 14, 15,
16, 17, 18, 19, 20);
Run Code Online (Sandbox Code Playgroud)