user1300835
user1300835

Reputation: 15

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.

Upvotes: 0

Views: 73

Answers (2)

Mohit Jain
Mohit Jain

Reputation: 30489

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

Upvotes: 1

BLUEPIXY
BLUEPIXY

Reputation: 40145

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

Upvotes: 2

Related Questions