Reputation: 3715
I have the following code:
void main()
{
int a[3][4] = {{1,2,3,4},{11,12,13,14},{21,22,23,24}};
printf("%d\n",*a);
system("pause");
}
The output is the address of the first element of the array. Why? I expect this address to be dereferenced.
Upvotes: 0
Views: 102
Reputation: 148
A multidimensional array in C is contiguous. The following:
int a[4][5];
consists of 4 int[5]s laid out next to each other in memory.
An array of pointers:
int *a[4];
is jagged. Each pointer can point to (the first element of) a separate array of a different length.
a[i][j] is equivalent to ((a+i)+j). See the C11 standard, section 6.5.2.1:
The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2)))
Thus, a[i][j] is equivalent to (*(a+i))[j], which is equivalent to ((a+i)+j).
This equivalence exists because in most contexts, expressions of array type decay to pointers to their first element (C11 standard, 6.3.2.1). a[i][j] is interpreted as the following:
a is an array of arrays, so it decays to a pointer to a[0], the first subarray. a+i is a pointer to the ith subarray of a. a[i] is equivalent to *(a+i), dereferencing a pointer to the ith subarray of a. Since this is an expression of array type, it decays to a pointer to a[i][0]. a[i][j] is equivalent to ((a+i)+j), dereferencing a pointer to the jth element of the ith subarray of a.
Note that pointers to arrays are different from pointers to their first element. a+i is a pointer to an array; it is not an expression of array type, and it does not decay, whether to a pointer to a pointer or to any other type.
and for some reason printing *a in single dimensional array will print the first element of the array whereas *a in a multidimensional array will print a random number. Why is this so?
The output is the address of the first element of the array. Why?
printf("%d\n",*a);
*a will be equivalent to a[0] that prints first element of the array.
Upvotes: 1
Reputation: 2431
To get the content you might want to dereference twice. The first element can be accessed by:
**a
or
*a[0]
Upvotes: 3