Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(arr + 2) is equivalent to *(arr + 2) . How?

Tags:

arrays

c

pointers

I am studying how to display elements of 2D array with the help of pointers. Here is the code I tried:

#include<stdio.h>  

int main(){

    int arr[3][2] = {  

    {7, 8},
    {6,3},
    {3,4}
    };

    printf("%u\n", (arr + 2));
    printf("%u\n", *(arr + 2)); 
}

Output:

6487616
6487616

I am expecting output of *(arr + 2) to be 3. How is it the same as (arr + 2)?

like image 819
dave Avatar asked Aug 28 '18 16:08

dave


2 Answers

A 2D array is really an array of arrays.

The expression arr + 2 has type int (*)[2], while *(arr + 2) has type int [2]. When printing the former, you have a pointer so that value of the pointer is printed. In the latter case, you have an array which decays to a pointer to the first element. So *(arr + 2) decays into arr + 2, which is the same as the first expression.

Going into more detail on arr + 2, arr has type int [3][2]. When you add an integer value to it, it decays to a pointer to the first member, so arr decays to type int (*)[2], and arr + 2 also has that type, and points to the subarray containing { 3, 4 }.

Also note that pointers should be printed with the %p format specifier, and that the pointer must be casted to void *, otherwise you invoke undefined behavior. In this case you were "lucky" that they happened to print the same thing.

To get the output of 3 you were expecting, you need to dereference one more time:

*(*(arr + 2))
like image 86
dbush Avatar answered Sep 18 '22 17:09

dbush


arr is an array of arrays of int. On almost any use an array is converted to a pointer to its first element. So arr gets converted to a pointer to an array of int.

OK, arr gets converted to a pointer to an array of int, so (arr+2) is of the same type, that is, a pointer to an array of int.

Now *(arr+2) is the thing (arr+2) points to. That is, an array of int.

Now since it's an array of int, it gets converted to a pointer to its first element. So *(arr+2) gets converted to a pointer to int. Note it is not an int and is unlikely to be equal to 3.

Now how come (arr+2) and *(arr+2) dosplay the same? They are a pointer to an array and a pointer to its first element. Although these pointets are of different types, they represent the same address, because the address of any array is the same as the address of its first element.

like image 27
n. 1.8e9-where's-my-share m. Avatar answered Sep 20 '22 17:09

n. 1.8e9-where's-my-share m.