langford_js
langford_js

Reputation: 23

Modify pointer inside class

I'm having a trouble manipulating a pointer inside a class.

#include <iostream>

using namespace std;

class myClass {
public:
    void modifyPointer(float *pointer);
};

void myClass::modifyPointer(float *pointer) {
    pointer = new float[3];
    pointer[0] = 0;
    pointer[1] = 1;
    pointer[2] = 2;
    cout << "Address: " << pointer << endl;
}

int main()
{
    float* pointer;
    myClass object;
    object.modifyPointer(pointer);
    cout << "Address: " << pointer << endl;
    cout << "Values: " << pointer[0] << "," << pointer[1] << "," << pointer[2]
        << std::endl;

    return 0;
}

When I print the pointer inside the class I get its address, but in the main program I get a 0 address and a seg fault when printing values. What am I wrong in how to modify this pointer?

Upvotes: 0

Views: 317

Answers (2)

Ron
Ron

Reputation: 15521

Pointers are just like any other objects. Passing an object as an argument by value creates a copy of that object. This means the original pointer in main() remains unaffected. And since it is unaffected and not initialized, accessing an array out of bounds with pointer[any_index] results in undefined behavior. Pass by reference instead:

void modifyPointer(float*& pointer)

Upvotes: 3

cigien
cigien

Reputation: 60258

You are taking the pointer by copy, so you don't see the changes in main. You need to take the pointer by reference, like this:

void myClass::modifyPointer(float * &pointer) {
   pointer = new float[3];
   // ...
}

You have to change the declaration of this function as well, of course.

Here's a working demo.

Upvotes: 3

Related Questions