相关疑难解决方法(0)

C在结构中初始化数组

我想在结构中包含一个可变长度数组,但是在正确初始化它时遇到了问题.

struct Grid {
  int rows;
  int cols;
  int grid[];
}

int main() {
  struct Grid testgrid = {1, 3, {4, 5, 6}};
}
Run Code Online (Sandbox Code Playgroud)

我尝试的一切都给了我一个'错误:灵活数组成员的非静态初始化'错误.

c struct

22
推荐指数
2
解决办法
5万
查看次数

struct中间的可变长度数组 - 为什么这个C代码对gcc有效

使用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)

c gcc c99 variable-length-array c11

22
推荐指数
1
解决办法
5777
查看次数

未记载的GCC C++ 11扩展?捕获lambda捕获列表中的任意表达式

奇怪的是,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)

c++ lambda gcc c++11

13
推荐指数
1
解决办法
555
查看次数

结构中可变长度的数组

我创建了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)

我收到一个错误消息,说图像的定义中未定义宽度和高度。我不明白为什么会收到该错误以及如何解决该错误

c arrays struct variable-length-array

4
推荐指数
2
解决办法
4934
查看次数

标签 统计

c ×3

gcc ×2

struct ×2

variable-length-array ×2

arrays ×1

c++ ×1

c++11 ×1

c11 ×1

c99 ×1

lambda ×1