Quote:
|
Originally Posted by 357mag
But I do have a question. Why do I have to write sum += pn[i]? I would think
that I need to tell the compiler to get at the value that is in the element in order to add it to the sum. So I would think I would have to write
sum += *pn[i]. But of course the compiler complains if I do that. Seems to
me that pn[i] would simply produce the addresses of the integers.
|
With C and C++, you can use subscript notation on both actual arrays, and pointers. When you have an array, the array name by itself (ie, with no subscript) evaluates to the address of the first element. For example:
int array[5];
int *ptr = array;
See how I assign the array to the pointer? Obviously, this won't copy the contents of the array; instead, it copies the array's address. Likewise, I can use array notation- that is, subscripting- with the pointer:
array[3] = 817;
std::cout << ptr[3]; // prints '817'
In a similar manner, you can use pointer notation with arrays:
*(array+3) = 123;
std::cout << *(ptr+3); // prints '123'
In essence, a subscript is a shorthand for pointer notation:
std::cout << ptr[4];
std::cout << *(ptr+4); // semantically the same as the above line
std::cout << *(4+ptr); // same again, since addition is commutative
std::cout << 4[ptr]; // looks funny, but it's the same too
Now, if you stick in your asterisk along with the subscript, as you suggest, you are attempting to use a pointer to int as a pointer to pointer to int:
*ptr[x] = 5;
*(*(ptr + x)) = 5; // same as above, but makes the error more obvious
Hopefully, this will clear up the pointer issues. I also recommend reading the pointer tutorial in DaWei's signature.