在struct中声明int数组

Bob*_*Bob 16 c arrays struct

在C中,我定义了struct下面看到的内容,并希望将其初始化为内联.foos初始化后,结构中的字段和数组都不会更改.第一个块中的代码工作正常.

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

typedef struct Foo Foo;

int tmp[] = {11, 22, 33};
struct Foo foos[] = { {123, tmp} };
Run Code Online (Sandbox Code Playgroud)

但是,我真的不需要这个tmp领域.实际上,它只会使我的代码混乱(这个例子有点简化).所以,相反我想声明的值some_array的声明内foos.但是,我无法获得正确的语法.也许这个领域some_array应该有不同的定义?

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
};
Run Code Online (Sandbox Code Playgroud)

Ber*_*e92 27

首先,有两种方式:

  • 你知道数组的大小
  • 你不知道那个尺寸.

在第一种情况下,它是一个静态编程问题,并不复杂:

#define Array_Size 3

struct Foo {
    int bar;
    int some_array[Array_Size];
};
Run Code Online (Sandbox Code Playgroud)

您可以使用此语法填充数组:

struct Foo foo;
foo.some_array[0] = 12;
foo.some_array[1] = 23;
foo.some_array[2] = 46;
Run Code Online (Sandbox Code Playgroud)

当你不知道数组的大小时,它是一个动态编程问题.你必须问大小.

struct Foo {

   int bar;
   int array_size;
   int* some_array;
};


struct Foo foo;
printf("What's the array's size? ");
scanf("%d", &foo.array_size);
//then you have to allocate memory for that, using <stdlib.h>

foo.some_array = (int*)malloc(sizeof(int) * foo.array_size);
//now you can fill the array with the same syntax as before.
//when you no longer need to use the array you have to free the 
//allocated memory block.

free( foo.some_array );
foo.some_array = 0;     //optional
Run Code Online (Sandbox Code Playgroud)

其次,typedef非常有用,所以当你写这个时:

typedef struct Foo {
   ...
} Foo;
Run Code Online (Sandbox Code Playgroud)

它意味着用这个替换"struct Foo"字:"Foo".所以语法是这样的:

Foo foo;   //instead of "struct Foo foo;
Run Code Online (Sandbox Code Playgroud)

干杯.


Yu *_*Hao 17

int *some_array;
Run Code Online (Sandbox Code Playgroud)

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

struct Foo {
  int bar;
  int some_array[3];
};
Run Code Online (Sandbox Code Playgroud)

还有一件事,重点typedef struct Foo Foo;是使用Foo而不是 struct Foo.你可以像这样使用typedef:

typedef struct Foo {
  int bar;
  int some_array[3];
} Foo;
Run Code Online (Sandbox Code Playgroud)