我想在结构中包含一个可变长度数组,但是在正确初始化它时遇到了问题.
struct Grid {
int rows;
int cols;
int grid[];
}
int main() {
struct Grid testgrid = {1, 3, {4, 5, 6}};
}
Run Code Online (Sandbox Code Playgroud)
我尝试的一切都给了我一个'错误:灵活数组成员的非静态初始化'错误.
使用VLA(可变长度数组)有一些奇怪的代码,它被gcc 4.6视为有效C(C99,C11):
$ cat a.c
int main(int argc,char**argv)
{
struct args_t{
int a;
int params[argc]; // << Wat?
// VLA in the middle of some struct, between other fields
int b;
} args;
args.b=0;
for(args.a=0;args.a<argc;args.a++)
{
args.params[args.a]=argv[0][0];
args.b++;
}
return args.b;
}
Run Code Online (Sandbox Code Playgroud)
此代码编译时没有警告:
$ gcc-4.6 -Wall -std=c99 a.c && echo $?
0
$ ./a.out ; echo $?
1
$ ./a.out 2; echo $?
2
$ ./a.out 2 3; echo $?
3
Run Code Online (Sandbox Code Playgroud)
同样的-std=c1x:
$ gcc-4.6 -Wall -std=c1x a.c && …Run Code Online (Sandbox Code Playgroud) 奇怪的是,GCC 4.7.2似乎对以下代码没有任何问题:
template<typename T>
T&& identity(T&& x1) {
return std::forward<T>(x1);
}
int main(int, char**) {
int x1 = 1;
int &x2 = identity(x1);
auto f = [&x1]() mutable {
x1 = x1 + 1;
};
auto g1 = [y=x2+1]() {
static_assert(std::is_same<decltype(y), const int>::value, "fail");
std::cout << "g1: " << y << std::endl;
};
auto h1 = [y=identity(x1)+1]() {
static_assert(std::is_same<decltype(y), const int>::value, "fail");
std::cout << "h1: " << y << std::endl;
};
auto g2 = [&y=x2]() {
static_assert(std::is_same<decltype(y), int&>::value, "fail");
std::cout …Run Code Online (Sandbox Code Playgroud) 我创建了2个结构来表示C中的图像(一个像素和一个图像)。
typedef struct pixel {
unsigned char red;
unsigned char green;
unsigned char blue;
};
typedef struct image {
int width;
int heigth;
struct pixel pixels[width][heigth];
};
Run Code Online (Sandbox Code Playgroud)
我收到一个错误消息,说图像的定义中未定义宽度和高度。我不明白为什么会收到该错误以及如何解决该错误