简体   繁体   中英

C initialize pointer to array in array initializator

I need to initialize array of this structure:

struct a {

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

My code looks like this;

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

This will compile, but segfaults, when program tries to access first element of field.

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

You should use something like (Adding to BLUEPIXY's answer)

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

Further reading: equivalence of pointers and arrays in C

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM