简体   繁体   中英

How to use int point to struct in c

i use int8_t* to point the struct,and i can use cout to print the " num " data, but how to print the " b " data?

here is my code

struct A_T{
    int num;
    char *b;
};
int main()
{
    A_T *a=new A_T();
    a->num=10;
    a->b="aaa";
    int8_t *p;
    p=(int8_t*)a;
    cout<<a->num<<endl;
    cout<<*p<<endl;
    return 0;
}

cout<<*p<<endl can print the " num " data is 10, but when i use cout<<*(p+1)<<endl to print " b " data, it prints nothing.

can you help me?

thank you

It's painful but this might work for you

#include <stddef.h>

cout << *(char**)(p + offsetof(A_T, b)) << '\n';

You could use from this 'cout << ((A_T *)p)->b<<endl;' instraction inorderto access member b of struct.

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