tags:

views:

71

answers:

2
+1  Q: 

Pointer to Arrays

i am using a pointer to an array of 4 integers as int(*ptr)[4]

using the following code in which m pointing to a 2-D array using this pointer

int arr[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12}};

int (*ptr)[4]= arr[4];

int m= (*ptr)[2];

what will be the value in "m"...

i need to find the value of element arr[1][2] how can i get it using pointer ptr?

A: 

Ptr doesn't point to anything and probably doesn't even compile, since [4] is outside the bounds of either the [3] or the [4] of the original array.

If you need to find arr[1][2] then you need int (*ptr)[4] = arr[1]; int m = ptr[2];

DeadMG
`int (*ptr)[4] =
AndreyT
@nitinpuri, yes it will be out of bounds - `arr` only has 3 elements, so the maximum index is 2.
Carl Norum
Wix
first part is done but int m= (*ptr)[2] does not point to element 3 of 4 element array..
Reply guys......
Its done... thanks...your thing worked...
Then mark my answer as the answer.
DeadMG
+1  A: 

Multi-dimensional arrays are really one dimensional arrays with a little syntaxic sugar. The initialization you had for ptr wasn't an address. It should have been

int *ptr[4] = { &arr[0][0], &arr[1][0], &arr[2][0], &arr[3][0]};

You can also leave the 4 out and just use

int *ptr[] = { &arr[0][0], &arr[1][0], &arr[2][0], &arr[3][0]};

I made a few modifications to your code below. Note the two sections with the printf. They should help to demonstrative how the values are actually laid out in memory.

#define MAJOR 3
#define MINOR 4
int arr[MAJOR][MINOR]={{1,2,3,4},{5,6,7,8},{9,10,11,12}};

int (*ptr)[4];
int *p = &arr[0][0];

// init ptr to point to starting location in arr
for(i = 0; i < MAJOR; i++) {
    ptr[i] = &arr[i][0];
}

// print out all the values of arr using a single int *
for(i = 0; i < MAJOR * MINOR; i++) {
    printf(" %d", *(p + i) );
}

for(i = 0; i < MAJOR; i++) {
  for(j = 0; j < MINOR; j++) {
     printf( " %d", *(p + i * MAJOR + j) );
  }
  printf("\n");
}
Jim Tshr