0

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.

3
  • 2
    Because you haven't allocated memory for the members a and b. Commented Oct 16, 2014 at 6:54
  • 4
    This will not compile ... This is not valid C at all. Please come back when you have real code that doesn't work. Voting to close. Commented Oct 16, 2014 at 6:58
  • I'm with @JensGustedt. Enable warnings in your compiler and you will immediately see this code is really, really wrong. gcc -Wall -Wextra -Werror for example. Commented Oct 16, 2014 at 7:00

2 Answers 2

2
struct a a[] = 
{
  {(int[]){1,2},(int[]){3,4}, 2},
  {(int[]){1},(int[]){3}, 1}
};
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

struct a[] = ...? Really?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.