![]() |
Getting the wrong answer
I've got this program that uses the new operator with an array. I'm studying pointers and I read that you can use the new operator with an array and a pointer if you don't know how big the array is going to be. So I wrote this program that asks the user how many elements he would like in his array. Then he inputs that. Next, it asks him to enter the values for the elements. Then it inputs that. Finally, I want the program to simply output the sum of the elements. But I'm getting the wrong answer for the sum. I'm just kind of doing this by myself, my books don't show examples similar to this so here is my program:
:
int main() |
Well I re-wrote the program and now it looks like I'm getting the correct answer:
:
for (int i = 0; i < max; i++)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. |
Declaring an array with a length that is determined at runtime is not supported by many compilers. You might want to refer to the applicable standards, as well as the compliance of various compilers to those standards.
|
Well it appears to work fine with my compiler. I'm using Microsoft Visual Studio 2005.
|
You also need to understand the reactions of the compiler to your syntax. pn [i] is a reference to a specific element of pn. Dereferencing that as *pn[i] will tell the compiler that pn[i] is a pointer. That might be in line with what pn actually holds in its elements, and it might not.
The standard requires that the name of an array be convertible to a pointer to that array. They are still not the same thing. If you examine the emitted machine code, you will see that there is difference of a level of indirection. The language does us many 'favors' in order to ease our task, but those favors often introduce some ambiguities. You might want to have a peep at the pointer tutorial referenced in my signature. |
Quote:
:
int array[5];:
array[3] = 817;:
*(array+3) = 123;:
std::cout << ptr[4];:
*ptr[x] = 5; |
Quote:
|
| All times are GMT -5. The time now is 2:38 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC