简体   繁体   中英

how to print value which pointer member pointing to in C

I have a struct

struct c
{
    int *id;
    int type;   

} obj;

how to print what obj.id pointing to? and also point obj->id to some int variable

I tried

printf("%p\n",obj.id);

but above is printing some address

and

printf("%d\n",obj.id);

in above compiler gives warning

format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’

Since obj.id is a pointer to an int (an int* ) you need to dereference it (using the * operator).

Full example:

#include <stdio.h>

struct c {
    int *id;
    int type;   
} obj;

int main() {
    int x = 10;
    obj.id = &x;
    printf("%d\n", *obj.id);
}

You need to dereference the pointer:

printf("%d\n",*(obj.id));

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