'Passing arrays of pointers in C++
Not sure what I'm doing wrong here. I'm trying to add a new element and up until the function ends it appears to have worked. But once I try to access anything in it after I get a segmentation fault.
This is just sample code I'm using to try and figure out what I'm doing wrong, with console output to help determine current values.
#include <iomanip>
#include <iostream>
using namespace std;
class foo
{
private:
int z;
public:
foo(int);
int getz();
void setz(int);
};
foo::foo(int zz)
{
z = zz;
}
int foo::getz()
{
return z;
}
void foo::setz(int zz)
{
z = zz;
}
void boo(foo** x, unsigned* n)
{
foo** b = new foo*[3];
for (int i=0; i<2; i++)
b[i] = x[i];
b[2] = new foo(5);
cout << x[0]->getz() << x[1]->getz();
delete[]x;
x = b;
cout << x[0]->getz() << ' ' << x[1]->getz() << ' ' << x[2]->getz();
b = nullptr;
(*n)++;
}
int main() {
foo** a = new foo*[2];
unsigned s = 2;
a[0] = new foo(1);
a[1] = new foo(2);
boo(a, &s);
cout << s;
cout << a[0]->getz();
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
