Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a+1 == *(a+1) in this example?

#include <iostream>

int main()
{
    int a[3][3] = {{22, 33, 44}, {55, 66, 77}, {88, 99, 100}};
    std::cout << a[1] << '\n' << a + 1 << '\n' << *(a + 1);
}
0x0013FF68
0x0013FF68
0x0013FF68

Why does a+1 == *(a+1)?

like image 728
Masoud Fard Avatar asked Nov 07 '14 22:11

Masoud Fard


People also ask

What is the difference between * A 1 and *( a 1 in C programming?

*a + 1 is equivalent to a[0] + 1 while *(a + 1) is equivalent to a[1]. The dereference operator '*' being prefix, has got higher precedence than the binary '+' operator. You don't have to allocate memory yourself for all variables. There are three kinds of memory in the C memory model: global variables, stack and heap.

What does double * num2 do?

double *num2;Declares and initializes an pointer variable named num2. c. Initializes a variable named *num2.

What does == mean in C programming?

The equal-to operator ( == ) returns true if both operands have the same value; otherwise, it returns false . The not-equal-to operator ( !=

What happens when you add 1 to a pointer?

Pointer Arithmetic Unlike regular numbers, adding 1 to a pointer will increment its value (a memory address) by the size of its underlying data type. To simplify the logic behind this, think of pointer arithmetic the same way you think about array indexing.


1 Answers

a + 1 is the address of the second element in a and could also be written as &a[1] (which is equivalent to &*(a + 1) by definition).

*(a + 1) is an lvalue referring to the second array. It's equivalent to a[1] by definition.
Just like with any other array to pointer decay, this lvalue decays to a pointer to the first element of the array it refers to, i.e. it decays to &a[1][0]. But that is equivalent to the address of that array object itself. So the value is the same as that of &a[1] ... which is precisely how we defined the value of the expression a + 1 above.

Note that the array is decayed to a pointer because the best match for the second insertion is operator<<(void const*). Consider

int (*p1)[3] = a + 1;

int (&p2)[3] = *(a + 1); // We could also have written *p1

int* p3 = p2; // The array-to-pointer decay

assert( static_cast<void*>(p1) == static_cast<void*>(p3) );
like image 77
Columbo Avatar answered Oct 12 '22 04:10

Columbo