Reputation: 93
int array[10] = {1,2,3,4,5,6,7,8};
int *ptr = array;
std::cout<<*(ptr+ 2); => O/P = 3
int (*arr_ptr)[10] = &array;
std::cout<<*(*arr_ptr+2); => O/P = 3
Whats the difference between these 2. I know what they mean, but if they give same result why do we have 2 different notations?
Upvotes: 3
Views: 188
Reputation: 2134
They are not in fact the same to the compiler, and will result in different assembly language being generated.
Here is some good reference on the difference: http://cplusplus.com/forum/articles/10/
Upvotes: 0
Reputation: 70078
After editing your question, following are the differences:
(1) int *ptr = array;
array
gets decayed to the pointer. ptr
is ideally allowed to point to any int[]
irrespective of its size
(2) int (*arr_ptr)[10] = &array;
arr_ptr
is a pointer to an int[10]
. It's very specific definition and you can never assign an array to arr_ptr
which has size other than 10
.
int array_2[20];
arr_ptr = &array_2; // error
Upvotes: 1
Reputation: 3951
Use the notation that you understand and that fits the problem domain. If your app has an array, then use array notation. If you have to push pointers around for some other reason, then the second version is appropriate.
Upvotes: 0
Reputation: 47468
The first case is the normal case: ptr
is a pointer to the first element of the array array
, and it is indexed (using *(ptr+2)
, which is a synonym for ptr[2]
) to access the third element of that array.
The second case is contrived: arr_ptr
is a pointer to the (enitre) array array
. It is first dereferenced (with *arr_ptr
) to yield the array itself, which is then used as an argument to binary +
, which causes it to get implicitly converted to a (nameless) pointer to its first element, which is then indexed in the same way *(<nameless pointer>+2)
and gives the same result.
Making those implicit conversions explicit, you could write
int *ptr = &array[0];
std::cout<<*(ptr+ 2);
int (*arr_ptr)[10] = &array;
std::cout<<*( &(*arr_ptr)[0] + 2 );
Upvotes: 3