Reputation: 1000
I have some idea about pointers and arrays. The array
int a[3]={1,2,3};
can be accessed in the following way
printf("array is %d,%d,%d\n",a[0],a[1],a[2]);
or using pointers
printf("array is %d,%d,%d\n",*(a+0),*(a+1),*(a+2));
But how could i access the same array if it is inside a structure ?
struct test{
int a[3];
}var={1,2,3};
one way is to access using subscript like below.
printf("array is %d,%d,%d\n",var.a[0],var.a[1],var.a[2]);
but how could i access the same array using base pointer just like a normal array?
printf("array is %d,%d,%d\n",var.*a,var.*(a+1),var.*(a+2));
the above line gives "error: expected identifier before '*' token" during compilation.
Upvotes: 1
Views: 90
Reputation: 123598
The expression var.a[0]
is parsed as (var.a)[0]
; think of the leading var.
as kind of a path name for the array object within the struct type1.
So, remembering that a[i]
is equivalent to *(a + i)
, and that in this case a
is var.a
, then the pointer equivalent is *(var.a + i)
.
Hence:
printf("array is %d, %d, %d\n", *var.a, *(var.a + 1), *(var.a + 2));
Stick with array notation when dealing with arrays; it's easier to deal with, somewhat easier to read, and not necessarily any slower than using a pointer expression.
Upvotes: 3
Reputation: 75062
Think simply.
#include <stdio.h>
struct test {
int a[3];
} var={{1,2,3}}; /* add {} */
int main(void) {
printf("array is %d,%d,%d\n",*var.a,*(var.a+1),*(var.a+2));
return 0;
}
Upvotes: 2
Reputation: 10605
printf("array is %d,%d,%d\n",*var.a,*(var.a+1),*(var.a+2));
In the case of the structure, var.a is the pointer.
Upvotes: 2