763 views
1 votes
1 votes

when I am passing a 2D array and function is declared like
func(int a[][6]) //This implies that a is going to an array of 6 columns ,rght now we don't know the rows fine ,but it is pointing to a 2D array .

but if I declare the function like

func(int (*a)[6]) //Now how is this notation correct for a to point to a 2D array since it implies that a is a pointer to an array of 6 elements so that implies that it would be pointing to a 1D array .Although we can increment it and get to another row of 2D array ,but still I am a bit confused with this notation .

I am unable to get the exact way in this pointer a would be pointing to the 2D array .

 

 

 

 

2 Answers

2 votes
2 votes

Hi 

we can write a[i] as *(a+i) .

as [] is left to right Associativity . expand it from left to right

a[i][j] can be written as ( *(a+i)) [j] = *( *(a+i) +j)  

when we pass an array , we pass address of first element in array, i.e a[0][0]

a[0][j] can be written as ( *(a+0))[j] = (*a)[j]

if we increment a then it will become (*(a+1))[j]

0 votes
0 votes

func(int a[][6])  // This implies that a is going to an array of 6 columns ,right now we don't know the rows fine ,but it is pointing to a 2D array .

I hope you are fine with this declaration. Here a will be having the address of first element a[0][0].

func(int (*a)[6]) //Now how is this notation correct for a to point to a 2D array since it implies that a is a pointer to an array of 6 elements so that implies that it would be pointing to a 1D array .I am unable to get the exact way in this pointer a would be pointing to the 2D array .

 

As you know passing an array is just sending Base address.

Now in given declaration "int (*a)[6]", as you have mentioned you can access the each row of 6 integers base address.Once you will do (a+1) it will increment to next row base address and so on.

To access the each element of that row you have to just do like below

 

int *t;

t = a;   // As you know a is a pointer to an array of 6 elements.

           // It means it can have address to such array of 6 elements.

          //  we are assigning that base address to a integer pointer.

          // Since integer pointer can hold the address of integer element.

          // (i.e. first element of first array)

int i;

for( i =0;i<6;i++)

   printf("%d", *(t+i);

 

This way you can access each elements of the 2-D array.

 

Related questions

0 votes
0 votes
2 answers
1
radha gogia asked Aug 2, 2015
836 views
int B [3];int *p = B; // why this is wrong?int (*p)[3] = B; // why this is correct?
0 votes
0 votes
2 answers
4
dhruba asked Jun 5, 2023
1,151 views
Binary search is performed on a sorted array of n elements. The search key is not in the array and falls between the elements at positions m and m+1 (where 1 ≤ m < n). ...