Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer Arithmetic with structures

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();
}
like image 986
RStyle Avatar asked Dec 13 '22 06:12

RStyle


1 Answers

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.

like image 93
Dave Avatar answered Dec 28 '22 19:12

Dave