C在数组初始化中初始化指向数组的指针

时间:2014-10-16 06:52:33

标签: c arrays initialization

我需要初始化这个结构的数组:

struct a {

   int *a;
   int *b;
   int count;
};

我的代码看起来像这样;

struct a[] = 
{
  {{1,2},{3,4}, 2},
  {{1},{3}, 1}
};

当程序试图访问字段的第一个元素时,这将编译但是段错误。

2 个答案:

答案 0 :(得分:2)

struct a a[] = 
{
  {(int[]){1,2},(int[]){3,4}, 2},
  {(int[]){1},(int[]){3}, 1}
};

答案 1 :(得分:1)

你应该使用类似的东西(添加到BLUEPIXY'答案)

static int arr1[] = {1, 2};
static int arr2[] = {3, 4};
static int arr3[] = {1};
static int arr4[] = {3};

struct a a[] = 
{
  {arr1, arr2, 2},
  {arr3, arr4, 1}
};

Live code here

进一步阅读:equivalence of pointers and arrays in C