Marco - 1 year ago 60

C++ Question

In my book, it says Pointers are addresses and have a numerical value. You can print out the value of a pointer as cout << (unsigned long)(p)

Write code to compare p,p+1,q, and q+1. Explain the results, Im not sure what the book wants me to so here's what I have. Does anyone Know if I am doing this right

`int num = 20;`

double dbl = 20.0;

int *p = #

double *q = &dbl;

cout << (unsigned long)(q) << endl;

q = q + 1;

cout << (unsigned long)(q) << endl;

cout << (unsigned long)(p) << endl;

p = p + 1 ;

cout << (unsigned long)(p) << endl;

Answer Source

Assuming it's the pointer arithmetic you have problems with, let my try to to show how it's done in a more "graphical" way:

Lets say we have a pointer variable `ptr`

which points to an array of integers, something like

```
int array[4] = { 1234, 5678, 9012, 3456 };
int* ptr = array; // Makes `ptr` point to the first element of `array`
```

In memory it looks something like

+------+------+------+------+ | 1234 | 5678 | 9012 | 3456 | +------+------+------+------+ ^ ^ ^ ^ | | | | ptr ptr+1 ptr+2 ptr+3

_{The first is technically ptr+0}

When adding one to a pointer, you go to the next element in the "array".

Perhaps now you start to see some similarities between pointer arithmetic and array indexing. And that is because there *is* a common thread here: For any pointer *or array* `p`

and valid index `i`

, the expression `p[i]`

is exactly the same as `*(p + i)`

.

Using the knowledge that `p[i]`

is equal to `*(p + i)`

makes it easier to understand how an array can be used as a pointer to its first element. We start with a pointer to the first element of `array`

(as defined above): `&array[0]`

. This is equal to the expression `&*(array + 0)`

. The address-of (`&`

) and dereference (`*`

) operators cancel out each, leaving us with `(array + 0)`

. Adding zero to anything can be removed as well, so now we have `(array)`

. And finally we can remove the parentheses, leaving us with `array`

. That means that `&array[0]`

is equal to `array`

.