Pointers and Classes

Dec 12, 2013 at 11:45pm
I have one class for vectors called v3f and it has a public field variable pointer
int* data;

its constructor is
v3f(int x, int y, int z);

its defined as
1
2
3
4
5
v3f::v3f(int x, int y, int z)
{
   int temp[] = {3,x,y,z};
   this->data = temp+1;
}


The problem is that when i attempt to access the data pointer through an instance of the class through main() it displays nonsense

1
2
3
4
5
6
7
int main()
{
   v3f vctr(1,2,3);
   cout << vctr.data[0] << "\n";
   cout << vctr.data[1] << "\n";
   cout << vctr.data[2] << "\n";
}


it should be outputting 1,2,3. But it is not...any ideas?
Thanks alot!!


Dec 13, 2013 at 12:13am
closed account (S6k9GNh0)
temp is just that... it's temporary. When the function exits, the memory is freed.

If you were to try and modify that data, it would be a segmentation fault as you don't own that memory.

Instead, do something like:

1
2
3
4
5
struct v3f {
    int data[3];

    v3f(int x, int y, int z) : data{x, y ,z} { }
};


Not sure if that's correct but the idea is there. data is now the size of three integers and will last as long as the object instance does.

EDIT: Removed parenthesis around array intializer. You need a C++11 compliant compiler.
Last edited on Dec 13, 2013 at 12:20am
Dec 13, 2013 at 12:29am
As @computerequip says, int temp[] = {3,x,y,z}; is storage allocated on the stack during the call to v3f::v3f(int x, int y, int z), and is released when it returns, and reused by subsequent calls to other functions. Meanwhile int* data; is pointing into this area, which will have anything from return addresses, register saves, and other automatic variables. So you _should_ see garbage.

Maybe, depending what you're trying to do, you should declare it as int data[4]; within the class, and initialise it in the constructor.
Topic archived. No new replies allowed.