tags:

views:

166

answers:

3

Hi, 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

+2  A: 

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.

Johannes Schaub - litb
A: 

This should work as well:

*( Myval[0] + 1 )
Alan Haggai Alavi
Can we use any type of typecase operations as an alternative if we want??
sorry,typecast operations??
@Maddy: Sorry, either I did not understand your question, or I do not know the answer. :-)
Alan Haggai Alavi
its ok.I just got it
+4  A: 

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.

Charles Bailey