1

I am facing an error: request for member data in something not a structure or union. I am passing the address of a structure receiver_data in a structure global_vals to a function in another file.

The init_func function receives the address as a pointer. I used the arrow operator since its a pointer but I cant seem to access the structure. Both memory addresses &val.receiver_data and *ptr are the same so I'm not quite sure where went wrong

Would appreciate if someone can point out my mistake.

The components are split across various source/ header files with the following structure.

  • main.c
  • func_init.c
  • datatypes.c

main.c

global_vals val;
void main(void)
{
    val.receiver_data.data = 10;
    init_func(&val.receiver_data);
}

func_init.c

void init_func(int *ptr_data)
{
    printf("%d\n", ptr_data->data);
}

datatypes.h

typedef struct Receiver {
    int data;
} Receiver;
    
typedef struct {
    Receiver receiver_data;
    // truncated
} global_vals;

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Wb10
  • 89
  • 4
  • 1
    As far as I know, `int* ptr_data` cannot have any members, like `->data`. It's an integer. – Captain Trojan Mar 03 '21 at 11:35
  • Should be `void init_func(Receiver *ptr_data)` – Damien Mar 03 '21 at 11:36
  • That you don't get more compiler messages is because you don't declare the `init_func` function before you call it. If you did then you would be getting messages that you try to pass invalid arguments to the function. Always make it a habit to declare the functions you call, before you call them. – Some programmer dude Mar 03 '21 at 11:37
  • 1
    @Someprogrammerdude Or, you know, simply don't use a compiler which hasn't been updated in the past 22 years... implicit function declarations were removed from the C language during the previous millennium. – Lundin Mar 03 '21 at 11:48

2 Answers2

1

The function parameter

void init_func(int *ptr_data)
{
    printf("%d\n", ptr_data->data);
}

has the type int * that is it is a pointer to a scalar object. So this construction ptr_data->data is invalid because integers do not have data members like data.

It is not clear why the function is not declared like

void init_func( Receiver *ptr_data);

An alternative approach is to declare and define the function like

void init_func(int *ptr_data)
{
    printf("%d\n", *ptr_data);
}

and call it like

init_func(&val.receiver_data.data);

I hope that actually the function does something useful instead of just outputting an integer.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0
  • The compiler says:

error: request for member 'data' in something not a structure or union

  • The compiler points at the exact location of the bug:

    |     printf("%d\n", ptr_data->data);
    |                            ^~
    
  • The programmer thinks: Is ptr_data really a structure or union?

  • The programmer checks the declaration int *ptr_data. No, it is not.

Lundin
  • 195,001
  • 40
  • 254
  • 396