nobalG
nobalG

Reputation: 4620

regarding two dimensional arrays

if i have created an array like int marks[4][2]; then the name of the array must give me the address of the first element,as is in case of one dimensional array,but it is not so? & also
printf("%d",marks[0]); & printf("%d",marks); yield the same result?????????

Upvotes: 0

Views: 169

Answers (4)

Mahesh
Mahesh

Reputation: 34625

printf("%d",marks);

Giving a wrong format-specifier leads to undefined-behavior. marks leads to a pointer to 1D array( i.e., pointer pointing to the first element of first row ).

So, to print a pointer's content %p should be used instead.

printf("%p",marks);

And it seems you are trying to print the value at a location 0*0. So -

printf("%d",marks[0][0]);  // [m][n] is the way of accessing 2D array elements.

Upvotes: 2

aschepler
aschepler

Reputation: 72311

When you use %d in a printf format, the corresponding argument (after default promotions) MUST have type int. Since you broke that rule in both cases, anything could happen.

marks has type int[4][2] and decays to int(*)[2], which is not int.

marks[0] has type int[2] and decays to int*, which is not int.

(But I'm still surprised an actual implementation would output different addresses.)

Upvotes: 0

JCooper
JCooper

Reputation: 6525

It behaves as expected for me:

#include <stdio.h>

int main(int argC,char* argV[]) 
{

  int marks[4][2]={0};
  printf("%x %x %x\n"
         "%x %x %x\n"
         "%x %x\n",
         marks,marks[0],marks[0][0],
         *marks,&marks,**marks,
         &marks[0],&marks[0][0]);
  return 0;
}

Has output:

12ff44 12ff44 0
12ff44 12ff44 0
12ff44 12ff44

All pointers to the first element of the list (except the zero which is the first element of the list).

Upvotes: 1

Ammu
Ammu

Reputation: 5127

In C , for example A 2D array is treated as a 1D array whose elements are 1D arrays.So if you want to get the address of any of the elements you will have to use

printf("%8u\n",&a[i][j]);

Both the print statements print the same result because both marks and marks[0] are pointing to the starting of the first row of the two dimensional array.

Upvotes: 0

Related Questions