2

I am new to C, and I can't figure it out, why I am getting initialization incompatible poniter type warning.The relevant parts of the code are:

struct a {
  int address;
  B * apples[8];
} A;

struct b {
  int color;
} B;

I have an array of A's called a_list. What I am currently doing is:

B *b_list = a_list[i].apples;   // i being an index in for loop
b_list[6].color = 0;

The above works correctly, but throws the warning:

  Initialization from incompatible pointer type. 

In order to fix it, my reasoning is that I should be doing

B ** b_list = a_list[i].apples;  // as it is pointer to pointer. 
So now b_list basically points to a pointer which points to an array of 6, yea?
So: (*b_list)[6].color          // However this causes segmentation fault.

It was also working correctly when the struct A had B apples[8], rather than B* apples[8]. However, using this solution does not maintain the changes made in functions outside of where they were made.

Please advice.

niko
  • 9,285
  • 27
  • 84
  • 131
Catie
  • 555
  • 5
  • 12
  • 23

2 Answers2

1

A and B are not types, but instances of struct a and struct b. Perhaps you want to use the classic C idiom but you are missing a typedef:

typedef struct a {
    ...
} A;

Now struct a and A are the same thing.

In your last code snippet, (*b_list)[6].color should actually be (*b_list[6]).color or better yet b_list[6]->color.

K-ballo
  • 80,396
  • 20
  • 159
  • 169
0

It was also working correctly when the struct A had B apples[8], rather than B* apples[8]. However, using this solution does not maintain the changes made in functions outside of where they were made.

Pass a pointer to the object to such functions and your changes will persist outside of them. The reason they didn't is because you were passing the object by value.

Michael Goldshteyn
  • 71,784
  • 24
  • 131
  • 181