How to print a particular member of a structure using pointer arithmetic? I have a structure with 2 members. I want to print out member j
by manipulating the memory of the pointer to that structure.
#include <stdio.h>
#include <conio.h>
typedef struct ASD
{
int i;
int j;
}asd;
void main (void)
{
asd test;
asd * ptr;
test.i = 100;
test.j = 200;
ptr = &test;
printf("%d",*(ptr +1));
_getch();
}
Use the offsetof
macro provided in stddef.h
:
#include<stddef.h>
main()
{
asd foo = {100, 200};
unsigned char* bar = (void*)&foo;
printf("%d\n", *(int*)(bar+offsetof(asd, j)));
}
Any other way runs into padding/alignment issues.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With