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();
}
The pointer type needs to be right so that the increment adds the correct size:
Edit: As any C programmer should know, using pointer arithmetic to access struct members is useless and dangerous. Useless because the
->operation is much more concise and precise in accessing a named member, and dangerous because naive use of pointer arithmetic will result in a number of issues. However, pointer arithmetic is what the OP asked for, so pointer arithmetic is what he got.