I compiled your code with gcc and i got.
In function ‘main’:
error: ‘a’ undeclared (first use in this function)
p = &a;
^
note: each undeclared identifier is reported only once for each function it appears in
warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘struct test’ [-Wformat=]
printf("p[0] = %d\n",*(p+0));
^
warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘struct test’ [-Wformat=]
printf("p[0] = %d\n",*(p+1));
Assuming you meant p=&m, here is my explanation
printf("p[0] = %d\n",*(p+0));
printf("p[0] = %d\n",*(p+1));
First analyse whether deferring pointer like you did in printf function is correct or not.
The *(p+0) will give you the access to the struct test variabe m. As, you have assigned the address of a variable of type struct test to the pointer p, deferring pointer *p or *(p+0) will give you the access to the variable m. But the address assigned to the pointer is of a single variable not of the array of type struct test, deferring (p+1) will give you UNDEFINED BEHAVIOR. For example, *(p+1) would have worked if (not in printf statement)
struct test m[20];
struct test *p;
(*(p+0)).a=2;
(*(p+1)).a=5;
Is there a way to print all struct members using index?
You can. But there is no overloading of operators in c. So, you can achieve this by -
printf("a=%d, b=%d", p->a, p->b);
If pointer p points to array of type struct test, then you can use index in printf as
printf("a=%d, b=%d of %dth element", p[i].a, p[i].b, i);
My suggestion for your future code experimentation will be first analyse warning and error given by your code. The warnings can help to rectify most of the bugs in your code. I always compile my c/c++ code with gcc/g++ compiler and use flags like -Wall, -Wshadow, -Wextra. You can google a warning if you don't understand it.
p = &a;?p = &m.a;pis of typestruct test *while&m.ais of typeint *.