Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

User-defined object containing pointer breaks when stored in array

When I store a plain int in A and perform a simple get function:

#include <iostream>
class A
{
    int p;
public:
    void setint(int p_x);
    int getint();
};

void A::setint(int p_x) {p = p_x;} // set p (type int)

int A::getint() {return p;} // get p (type int)

int main()
{
    A arr_a[5];
    arr_a[0].getint();
}

it compiles and exits with code 0. However when I change int to int* and try to do the same:

#include <iostream>
class A
{
    int* p;
public:
    void setint(int p_x);
    int getint();
};

void A::setint(int p_x) {*p = p_x;} // set int pointed to by p (type int)

int A::getint() {return *p;} // get int pointed to by p (type int)

int main()
{
    A arr_a[5];
    arr_a[0].getint();
}

it compiles fine but exits with code 3221225477. Why is this so and is there still a way I can store pointers in A and store A in arrays?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In your 2nd case A arr_a[5] just create a array that contains 5 A. but
for every A, the pointer is an undefined number (maybe 0x0), so *p is a undefined behavior. You should add A::A() and A::~A() to manage your pointer in your class
just like this:

#include <iostream>
class A
{
    int *p;

public:
    A();
    ~A();
    void setint(int p_x);
    int getint();
};

A::A() : p(new int) {}
A::~A() { delete p; }

void A::setint(int p_x) { *p = p_x; } // set int pointed to by p (type int)

int A::getint() { return *p; } // get int pointed to by p (type int)

int main()
{
    A arr_a[5];
    arr_a[0].getint();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading