I am teaching myself C programming, using "Head First C", published by O'Reilly. (And a couple of other texts, besides.)
I got very hung-up during the book's introduction to pointers, by the example program on p.58. What threw me was a little call-out in the text, pointing to the line:
int *choice = contestants;
The call-out reads:
“choice” is now the address of the “contestants” array.
And, as far as I can tell, that's wrong. That line assigns *choice
to the value stored as the contestants
array, is that not so?
The book is correct. Pointers work differently from variables, and * works differently in different circumstances.
To start, you probably know that a pointer is just a variable containing the address to the location in memory of another item
When we use
int *choice
we create a pointer to an integer, which stores the address of the integer
In this case, I'm assuming contestants is an array. We'll assume it's an array of ints
int contestants[5] = [0,1,2,3,4];
Collections, such as arrays, are always stored as a pointer to the first element. The second element is therefore addressof_first_item + sizeof(element_stored)
.
Let's assume the address is 0x12345
, it's like this int contestants = 0x12345
And now we store that address in choice:
int *choice = contestants
In other words, it's a pointer to an integer, which happens to be the first element in the contestants array.
As a side note, we could also write it as:
int* choice = &contestants[0];
The other use case for the * operator with regards to pointers, is dereferencing. Dereferencing involves getting the value at the address pointed to by a pointer.
int value = *choice;
will give us an integer with a value of 0, because the address stored points to the first element