I'm working through some code for a class I'm taking, and since I'm not familiar with C++ I am confused by subscripting pointers.
My assumptions:
& prefixed to a variable name, gives you a pointer to the memory address of that value and is roughly inverse to * prefixed to a variable name, which in turn gives you the value that resides at a particular memory address.
Pointers are subscriptable, so that ptr[0] == ptr and ptr[n] == ptr + (n * data_bytes), where data_bytes depends on the particular type of the pointer (eg. 4 bytes wide for 32-bit ints).
The Problem:
When I want to subscript the memory address, I have to put it in a variable first, and I don't understand why I can't just subscript the variable directly.
Minimal Code Example:
#include <iostream> using namespace std; int main() { int val = 1; int *val_ptr = &val; cout << &val << endl; // works cout << val_ptr[0] << endl; // does not work // cout << &val[0] << endl; return 0; } Addendum
I am aware of some related questions, but they didn't really help me understand this specific issue.
I looked at:
- What are the differences between a pointer variable and a reference variable in C++?
- how does the ampersand(&) sign work in c++?
- subscript operator on pointers
- Subscripting integer variable using a pointer
and while this is almost certainly a duplicate (I will hardly be the first person that's confused by pointers), or maybe even has an answer that I overlooked in the linked questions, I'd appreciate any help!
[]is considered before&. Do(&val)[0]instead.ptr[0] == ptr and ptr[n] == ptr + (n * data_bytes)are both incorrect. We don't say that an address and the value at that address are==equal. For a pointerpand integeri, by definitionp[i] == *(p + i) == *(i + p) == i[p]. Note thatint(p + i) == int(p) + i * sizeof(*p), that is, the multiplication by element size applies during pointer arithmetic. Soptr + (n * bytes_per_element)is wrong, it would multiply by element size twice.ptr[n] == *(ptr + n), that's actually the definition of the[]operator (array subscripting). The parentheses are needed, due to operator precedence (which is what your question turned out to be about), if you write just*ptr + nthat would be the same asptr[0] + nnotptr[0 + n]