-1

I am trying to learn C,but I got stuck over the following piece of codes. What I understood from my basic knowledge about C is that the array name itself is a pointer pointing to the first element of the array. And elements in a 2D array is stored one row after the other.So I am trying print the values of elements in a 1D array and 2D array using array name as a pointer. But for the Code 1 it is working as I expected. But Code 2 is giving unexpected result (It is giving the starting addresses of each row). What is the reason for this to happen? I think something is wrong with my understanding. Can anybody clarify the mistake.

// Code 1
//-------
#include <stdio.h>
int main () {
    int array[2][3] = {{5, 7, 9}, {2, 5, 77}};
    int j;
    for (j=0; j < 6; j++)
        printf("%d\t", *(array+j));
    return 0;
}

//Code 2
//------
// #include <stdio.h>
// int main () {
//  int array[6] = {5, 7, 9, 2, 5, 77};
//  int j;
//  for (j=0; j < 6; j++)
//      printf("%d\t", *(array+j));
//  return 0;
// }
noufal
  • 940
  • 3
  • 15
  • 32

4 Answers4

2

Since multidimensional arrays are contiguous in memory, you can just grab a pointer to the first element of the array and use it as if it pointed to the first element of a one-dimensional array:

int array[2][3] = { { 5, 7, 9 }, { 2, 5, 77 } };
int *p = &array[0][0];

for (int i = 0; i < 6; i++)
    printf("%d\n", p[i]);

Your original attempt, *(array+j) was wrong because it's equivalent to array[j], which is an array itself, so you were trying to:

  1. print a pointer (array[j], being an array, decays into a pointer when passed to a function) as if it was an integer, using the %d format specifier - that invokes undefined behavior and at the same time it's not printing what you really wanted it to print;

  2. access the array out of bounds (array has only two elements, both are of type int [3], so you quickly run into undefined behavior when you access the 2nd, 3rd, ..., 5th element).

0

You should code

 for (int i=0; i<2; i++)
    for (int j=0; j<3; j++)
        printf("%d\t", t[i][j]);
 putc('\n');
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
0

For the two dimensional array, your code is not working. change

int j;
for (j=0; j < 6; j++)
    printf("%d\t", *(array+j));

to

for (int i=0; i<2; i++)
    for (int j=0; j<3; j++)
        printf("%d\t", *(*(array+i)+j));

For the pointer version, see @H2CO3's answer.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • [This is not what OP is looking for.](http://stackoverflow.com/questions/17905755/acessing-the-elements-of-a-1d-array-and-2d-array-in-c-using-pointer/17905774#17905774) –  Jul 28 '13 at 07:01
0

I don't think either of code will work.

sizeof(array) = 24 in both cases. Lets assume array starts at address 0x100 then array+1 will give you 0x100 + 0x18 = 0x118 not 0x100 + 0x4 = 0x104 as you are expecting.

0x18 = 24.

Rohan
  • 52,392
  • 12
  • 90
  • 87