0

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

Waqar
  • 8,558
  • 4
  • 35
  • 43
tianyu
  • 119
  • 1
  • 10

2 Answers2

4

It's painful but this might work for you

#include <stddef.h>

cout << *(char**)(p + offsetof(A_T, b)) << '\n';
john
  • 85,011
  • 4
  • 57
  • 81
1

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

Farhad Sarvari
  • 1,051
  • 7
  • 13