#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)
?
*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.
double *num2;Declares and initializes an pointer variable named num2. c. Initializes a variable named *num2.
The equal-to operator ( == ) returns true if both operands have the same value; otherwise, it returns false . The not-equal-to operator ( !=
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.
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) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With