在struct中声明int数组 [英] Declaring int array inside struct

查看:78
本文介绍了在struct中声明int数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C语言中,我定义了如下所示的 struct ,并希望内联初始化它.初始化后,结构内的字段或数组 foos 都不会更改.第一块中的代码可以正常工作.

In C, I have defined the struct seen below, and would like to initialize it inline. Neither the fields inside the struct, nor the array foos will change after initialization. The code in the first block works fine.

struct Foo {
  int bar;
  int *some_array;
};

typedef struct Foo Foo;

int tmp[] = {11, 22, 33};
struct Foo foos[] = { {123, tmp} };

但是,我真的不需要 tmp 字段.实际上,这只会使我的代码混乱(此示例有些简化).因此,相反,我想在 foos 的声明内声明 some_array 的值.但是,我无法获得正确的语法.也许字段 some_array 的定义应该不同?

However, I don't really need the tmp field. In fact, it will just clutter my code (this example is somewhat simplified). So, instead I'd like to declare the values of some_array inside the declaration for foos. I cannot get the right syntax, though. Maybe the field some_array should be defined differently?

int tmp[] = {11, 22, 33};
struct Foo foos[] = {
  {123, tmp},                    // works
  {222, {11, 22, 33}},           // doesn't compile
  {222, new int[]{11, 22, 33}},  // doesn't compile
  {222, (int*){11, 22, 33}},     // doesn't compile
  {222, (int[]){11, 22, 33}},    // compiles, wrong values in array
};

推荐答案

int *some_array;

在这里, some_array 实际上是一个指针,而不是数组.您可以这样定义它:

Here, some_array is actually a pointer, not an array. You can define it like this:

struct Foo {
  int bar;
  int some_array[3];
};

还有一点, typedef struct Foo Foo; 的要点是使用 Foo 而不是 struct Foo .您可以像这样使用typedef:

One more thing, the whole point of typedef struct Foo Foo; is to use Foo instead of struct Foo. And you can use typedef like this:

typedef struct Foo {
  int bar;
  int some_array[3];
} Foo;

这篇关于在struct中声明int数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆