user10603856
user10603856

Reputation:

Structure with pointer and array of structures in C

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);

Upvotes: 0

Views: 172

Answers (2)

Zach DeGeorge
Zach DeGeorge

Reputation: 105

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);
}

Upvotes: 0

P.P
P.P

Reputation: 121427

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!

Upvotes: 1

Related Questions