I am new to C++, and I am currently learning pointers. I am fully aware of the whole homework help restriction guideline stuff on this site.

I am slowly understanding the logic of pointers. I just need help with the coding syntax.

My assignment is as follows:

I have a program (shown below) that I must debug. I am required to fix up the program and modify it minimally in order for it to execute properly.

int main()
    {
        int arr[3] = { 5, 10, 15 };
        int *ptr = arr;

        *ptr = 10;          // set arr[0] to 10
        *ptr + 1 = 20;      // set arr[1] to 20
        ptr += 2;
        ptr[0] = 30;        // set arr[2] to 30

        while (ptr >= arr)
        {
	    ptr--;
            cout << *ptr << endl;    // print values
        }
    }

The notes written in the program are the objectives of the coded statements next to them.

How would I go about completing this task?

Any help would be greatly appreciated.

Thanks in advance.

>>How would I go about completing this task?
Did you try to compile the program? If you did, what errors did the compiler produce? If you did not compile it, why not? Hint: lines 7, 13 and 14 are wrong.

Here's what I tried:

#include <iostream>
using namespace std;

int main()
{
    int arr[3] = {5, 10, 15};
    int *ptr = arr;


    *ptr = 10;


    ptr += 1;
    *ptr = 20;


    ptr += 1;
    ptr[0] = 30;


    while(ptr >= arr)
    {
        cout << *ptr << endl;
                ptr--;
    }

}

I got the code to write out the right values....but it's in reverse order.
How would I go about reversing the output order?

Thanks.

while(ptr >= arr)
{
cout << *ptr << endl;
ptr--;
}

must be modified to

ptr=arr;
while(ptr <= arr+2)
{
cout << *ptr << endl;
ptr++;
}

If you want to modify the original program minimally,

*ptr + 1 = 20; // set arr[1] to 20

should be rewritten as

*(ptr + 1) = 20; // set arr[1] to 20

This is because * has higher precedence than +. Also interchange lines 13 & 14.

Also, this thread contains nothing specific to C++ & so, it should be posted in the C forum.

Thanks for the replies. I greatly appreciate the help.
I'll remember to post in the right thread next time.

Not

in the right thread

,

but in the right forum ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.