Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory map for a 2D array in C

Do you think what this discussion about memory-map of 2D array is correct? Especially this photo? Can you explain the theory?

Suppose we declare a 2D array in C like this:

int arr[3][3]={10, 20, 30, 40, 50, 60, 70, 80, 90};

Now, according to this discussion, the memory would be arranged like the following:

enter image description here

Now, I have written the following code to test this theory:

#include <stdio.h>

main()
{
    int arr[3][3]={10, 20, 30, 40, 50, 60, 70, 80, 90};
    printf("      arr==%d\n", arr);
    printf("  &arr[0]==%d\n", &arr[0]);
    printf("   arr[0]==%d\n", arr[0]);
    printf("&arr[0][0]=%d\n", &arr[0][0]);
    printf(" arr[0][0]=%d\n", arr[0][0]);
}
/*
Output:
========
      arr ==1245028
  &arr[0] ==1245028
   arr[0] ==1245028
&arr[0][0]==1245028
 arr[0][0]==10
Press any key to continue...
*/

Why the first 4 outputs are same?

like image 337
user366312 Avatar asked Jul 13 '11 03:07

user366312


People also ask

How are 2D arrays stored in memory in C?

A 2D array is stored in the computer's memory one row following another. The address of the first byte of memory is considered as the memory location of the entire 2D array.

What is 2D array in C with example?

The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices which can be represented as the collection of rows and columns. However, 2D arrays are created to implement a relational database lookalike data structure.


1 Answers

Your code just uses a plain multidimensional array, but the image describes an array of pointers, like the kind you usually make when malloc-ing things.

A multidimensional array is basically just a normal, flattened, array (in memory) with some extra syntatic sugar for accessing. So while it is possible to get a pointer from arr[i], there isn't an extra "variable" just to store this, as happens in your image.

To correct the image, remove the parts with the arr[0], arr[1]... and change the value of arr to 1245039 (the same as &arr[0][0]).

like image 104
hugomg Avatar answered Sep 18 '22 14:09

hugomg