Monday, April 16, 2018

Pointers the evil problems

Errors in code to fix  - don't cheat, but the answer is also on this page.  Try to use your debugger to isolate and to locate the errors.  Copy/paste this code and find the problems.

#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;
}







Solution
#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;
    ptr = value;                    //fix 2 - reset ptr to base address
    for (int i = 0; i < SIZE; i++)  //fix 3 - invalid index value
        *(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;
}

No comments:

Post a Comment