Maddy
Maddy

Reputation:

pointer to an array

I have a pointer to an array and i am unable to access the members of the array.To make it more precise,plz see the code below:

       int struc[2] = {6,7};
       int (*Myval)[2];
       Myval =&struc;
         Now the Myval is pointing to the start of the array and upon dereferencing the pointer we would get the 1st element of the array i.e


      printf("The content of the 1st element is %d\n",(*Myval[0])); 
      gives me the first elemnt which is 6.            
      How would i access the 2nd elemnt of the array using the same pointer.

If i would do Myval++,it would increment by 8 since the size of the array is 8. any suggestions or idea??

Thanks and regards Maddy

Upvotes: 1

Views: 521

Answers (3)

CB Bailey
CB Bailey

Reputation: 791441

I think that while int (*)[2] is a valid type for pointing to an array of two ints, it is probably overkill for what you need, which is a pointer type for accessing the members of an array. In this case a simple int * pointing to an integer in the array is all that you need.

int *p = struc; // array decays to pointer to first element in assignment

p[0]; // accesses first member of the array
p[1]; // accesses second member of the array

As others have indicated, if you do use a pointer to an array, you have to dereference the pointer before using a subscript operation on the resulting array.

int (*Myval)[2] = &struc;

(*Myval)[0]; // accesses first member of the array
(*Myval)[1]; // accesses second member of the array

The C declaration syntax of 'declaration mirrors use' helps here.

Upvotes: 4

Alan Haggai Alavi
Alan Haggai Alavi

Reputation: 74202

This should work as well:

*( Myval[0] + 1 )

Upvotes: 0

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 506847

You would not dereference, but subscript, like with other pointers

Myval[0][1] // accesses second element

The first [0] is probably a little confusing, since it suggests that you are handling with an array. To make clear that you are working with a pointer, i would use dereferencing

(*Myval)[1] // accesses second element

The (*Myval) dereferences the array pointer and yields the array, and the following subscript operation addresses and dereferences the item you want.

Upvotes: 2

Related Questions