View Single Post
Old Jul 3rd, 2007, 8:42 AM   #6
lectricpharaoh
Caffeinated Neural Net
 
lectricpharaoh's Avatar
 
Join Date: Jun 2005
Location: Dry west coast of Canada
Posts: 1,010
Rep Power: 5 lectricpharaoh will become famous soon enough
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.
__________________
And once again, Probability proves itself willing to sneak into a back alley and service Drama as would a copper-piece harlot.
- Vaarsuvius, Order of the Stick
lectricpharaoh is offline   Reply With Quote