Problems with pointers

Here's a code and there are 3 problems and additions and/or modifications
I have to do in order for this code to run,
can anyone help, please?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
using namespace std;

int main(int argc, char **args) {
    int *ptr, *current;
    const int SIZE = 5;
    ptr = new int[SIZE];
    int value[SIZE];
    ptr = current = value;

    for (int i = 0; i <= SIZE; i++)
        value[i] = i * 2;
    for (int i = 0; i < SIZE; i++) {
        cout << *ptr << endl;
        ptr++;
    }

    cout << *(--ptr) << endl;
    for (int i = 0; i < SIZE; i++) {
        cout << *current << endl;
        current++;
    }

    cout << *(ptr) << endl;
    cout << *(--current) << endl;

    for (int i = 0; i <= SIZE; i++)
        *(ptr++) = i * 2;

    for (int i = 0; ptr <= &value[SIZE - 1]; ptr += 1)
        *ptr = i++ * 2;
    ptr--;
    cout << "The value where pointer 'ptr' pointing to is:  " << *ptr << endl;

    return 0;
}
Last edited on
A couple of problems:

Take a look at line 7 and 9: One assignment overrides the other.

Line 11: It will be out of bounds. See line 13 for how to correct it.
Line 27: The same problem as line 11.
Line 28: What is the value of ptr at that time? I.e. is it at the start position or not?
Line 31: Basically the same as line 27, but at least it will not go out of bounds.
Line 33: Will also be out of bounds.

It is example for how not to do it.
thanks!!
Topic archived. No new replies allowed.