简体   繁体   中英

error: request for member data in something not a structure or union despite using arrow operator

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;

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.

  • 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM