0

I'm trying to learn about nested structures and pointers in C. I made this as a test:

typedef struct xyz xyz_t;
struct xyz{
    int x, y, z;
};

xyz_t array[] = {
    {.x = 14, .y = 16, .z = 18}, 
    {.x = 34, .y = 36, .z = 38}, 
    {.x = 64, .y = 66, .z = 68},
};

typedef struct blue blue_t;
struct blue 
{
   int  *pointer;
};

int main() 
{
    blue_t red;
    red.pointer = &array;

    printf("%d",red.pointer[1].z);
}

The idea is to have the structure red have a pointer pointing to array, and then print f.ex. array[1].z.

What am I doing wrong? The compiler is telling me:

assignment from incompatible pointer type

[-Wincompatible-pointer-types] red.pointer = &array;

request for member x in something not a structure or union printf("%d",red.pointer[2].x);

Community
  • 1
  • 1
  • 2
    Why is `pointer` declared as pointing at an `int`? – StoryTeller - Unslander Monica Nov 04 '18 at 15:30
  • 1
    You create a type-alias `xyz_t`, which from that point can be used like any other native type (e.g. `int`). So a pointer to `xyz_t` is simply `xyz_t *`. – Some programmer dude Nov 04 '18 at 15:31
  • 2
    Furthermore, the type of `&array` is not `xyz_t *`, it is `xyz_t (*)[3]` since it's a pointer to the *array* and not a pointer to the first element. A pointer to the first element would be `&array[0]`. Or (since arrays naturally *decays* to pointers to their first element) plain `array`. – Some programmer dude Nov 04 '18 at 15:32

2 Answers2

1

The idea is to have the structure 'red' have a pointer pointing to 'array', and then print f.ex. array[1].z.

In that case, you need to have a pointer to xyz_t in your "blue" struct.

struct blue 
{
   xyz_t *pointer;
};

You need to drop the & from this red.pointer = &array;. array will be converted into a pointer to its first element in red.pointer = array; which is the correct type (to match LHS) See What is array decaying?; whereas &array is of type struct xyz (*)[3].

Aside, you could use a proper signature for main function (int main(void)). red could be a confusing a variable for a blue_t type!

P.P
  • 106,931
  • 18
  • 154
  • 210
0

This should be fixed. See if it helps:

typedef struct xyz{
    int x, y, z;
} xyz_t;

xyz_t array[] = {
    {.x = 14, .y = 16, .z = 18},
    {.x = 34, .y = 36, .z = 38},
    {.x = 64, .y = 66, .z = 68},
};

typedef struct {
    xyz_t *pointer;
} blue_t;

int main()
{
    blue_t red;
    red.pointer = &array;

    printf("%d",red.pointer[1].z);
}