Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

c - Pointers with two dimensional array

Please consider the following piece of code

#include <stdio.h>
#define ROW_SIZE 2
#define COL_SIZE 2

int main()
{
   int a[ROW_SIZE][COL_SIZE]={{1,2},{3,4}};

   // Base address:Pointer to the first element a 1D array
   printf("Base address of array:%p
",a);

   //The value at the base address: should be the address of 1st 1D array
   printf("Value at the Base address:%p
",*a);

   return 0;
}

Output obtained:

Sample Output:
Base address of array:0xbff77434
Value at the Base address:0xbff77434

Somehow, I am failing to understand the concept of the base address of a 2D array and the value at the base address which is inturn an address to a 1D array being same. Please explain.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Arrays aren't pointers, and in C, a multidimensional array is just an array of arrays. In many contexts, using the name of an array "decays" into a pointer to the first element of that array. That's what happens in both of your print statements. In the first case:

printf("Base address of array:%p
",a);

a becomes a pointer to the first element of the array - that is, a pointer to the first row of your array. In your case, that means you get a pointer of type int (*)[2].

In the second case:

printf("Value at the Base address:%p
",*a);

The same decaying happens, but then you dereference that pointer. That means you dereferenced that int (*)[2] pointer to the first row, leaving you with an array again (the first row). That array itself decays into a pointer to its first element, giving you a resulting int * pointer (to the first element of the first row).

In both cases the address is the same, since that's how the array is laid out in memory. If we said your 2D array started at address 0, it would look like this (assuming a 4 byte int type):

 Address       Value
    0            1
    4            2
    8            3
   12            4

The address of the first row and the address of the first element of the first row are both 0.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...