Pointers syntax - check my logic

Hi! I'm relearning pointers, and I wrote the following code to test out some syntax. Please comment on my comments, and add further explanation when necessary.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int* divisors;
divisors = new int[5];
divisors[0] = 5;
divisors[1] = 10;

cout << divisors << endl;//Here, 'divisors' = '&divisors [0]' because 'divisors' holds the address of the memory it points to (in this case, it's the first element of an array)
cout << &divisors << endl;//Address of the pointer itself
cout << *divisors << endl;//Value pointed by 'divisors' which = 'divisors [0]' because of the logic in 'divisors' = '&divisors [0]' mentioned above

cout << divisors [0] << endl;//Value of first element of array that divisors points to -> why not *divisors [0]??
cout << divisors [1] << endl;//Etc...

cout << &divisors [0] << endl;//Address of first element of array that divisors points to
cout << &divisors [1] << endl;//Etc...

//cout << *divisors [0] << endl; -> div.cpp:41:22: error: invalid type argument of unary '*' (have 'int') 


Particularly, why does 'divisors [0]' give a value and not '*divisors [0]'? Thank you!
closed account (zb0S216C)
benghaner1 wrote:
why does 'divisors [0]' give a value and not '*divisors [0]'? (sic)

Because *divisors[0] would be dereferencing the pointer at element 0 (first), not the pointer itself. Since divisors is an array of ints, dereferencing an int would be illegal. If you wanted to to this, it should be this:

1
2
std::cout << *( divisors + n ) << std::endl;
// n is the index of the requested element. 


Other than that, your comments seem correct to me. You do call delete[] don't you? :)P

Wazzak
Last edited on
Topic archived. No new replies allowed.