Karthick
Karthick

Reputation: 1000

How to access arrays inside a structure in pointer format?

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

Answers (3)

John Bode
John Bode

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.


1. This is a horrible analogy for a number of reasons, but it's the best I can come up with.

Upvotes: 3

MikeCAT
MikeCAT

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

Les
Les

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

Related Questions