initializing pointers to memory addresses or values?

What is the difference between initializing pointers to a memory address using the address operator like int *pointer = &x; or initializing it to a value like int *pointer = x; .. in other words how does p and q point to the same memory address in:
1
2
3
4
const int ARRAY_LEN = 100;
int arr [ ARRAY_LEN ];
int *p = arr;
int *q = &arr[0];
arr is not a value, it's also a memory address.
Arrays in C/++ are really weird. They are a distinct type but they frequently decay to pointers.
The only thing you can really do with arrays are (1) get their size with sizeof() and (2) take the address of the first element. More specifically, arr refers to the address of the first element.
And assign them to pointers/references to arrays.
And typedef them
And get typeinfo on them
etc
etc


Arrays are a unique type, just like anything else. AFAIK the only things you can't do with them are:
- compare them
- copy/assign them
- pass them as function parameters by value (requires copy)
- return them from functions (requires copy)



The only thing that's really "tricky" with arrays is that an array name can be implicitly cast to a pointer:

1
2
3
4
5
6
7
8
9
10
int arr[5]; // <- 'arr' is an array name, not a pointer
int* ptr = arr; // <- yet it can be cast to a pointer, so it can be confusing

// the difference should be noted, though.  Because you can have a pointer to an array:
int (*parr)[5] = &arr;  // <- points to the array itself, not to the first element
(*parr)[0] = x; // <- assigns arr[0]

// And references:
int (&rarr)[5] = arr;
rarr[0] = x;  // <- assigns arr[0] 
Topic archived. No new replies allowed.