Reputation: 11
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?
Upvotes: 1
Views: 337
Reputation:
The are multiple ways of accessing the value of element arr[1][2]
.
The method used in the code below is called pointer to pointer. By storing the address of the first element of pa[]
in pb
, one can use pb
to access elements of aa[][]
. One can use array notation aa[1][2]
, or one can use pointer notation *((*pb+1)+2)
. Both the notation approaches yield equivalent results.
#include<stdio.h>
int main()
{
int aa[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12}};
int *pa[3];
for(int i=0;i<3;i++)
pa[i]=aa[i];
pb=pa;
printf("pb[1][2]=%d\n",pb[1][2]); /*Array Notation*/
printf("arr[1][2]=%d",*(*(pb+1)+2)); /*Pointer Notation*/
}
Upvotes: 0
Reputation: 357
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");
}
Upvotes: 1
Reputation: 146910
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];
Upvotes: 0