Accessing array member created by another structure constructor

B

Bubba

Greetings to all,

here's the thing:

struct foo {
string a;
int b;

foo () {}
foo (string a, int b);
};

struct bar {
foo *data;
bar () {
bar (int m, int n)
void add (foo S, int i, int j);
};

foo::foo (string a, int b) {
foo::a = a;
foo::b = b;
}

bar::bar (int m, int n) {
foo* data = new foo[m*n*4];
}

Now I have a problem with function add, where I should access particular
element in data array of foo's and assign values from parameter, but don't
know exactly how. This doesn't work since it throws segmentation fault:

bar::add (foo S, int i, int j) {
data[(i*j*4)-].a = S.a;
data[(i*j*4)-].b = S.b;
}

What's the proper way to do that? I require array of foo's in the bar's
constructor.

Best regards,
 
V

Victor Bazarov

here's the thing:

struct foo {
string a;
int b;

foo () {}
foo (string a, int b);
};

struct bar {
foo *data;
bar () {
bar (int m, int n)
void add (foo S, int i, int j);
};

foo::foo (string a, int b) {
foo::a = a;
foo::b = b;

See FAQ section 10.
}

bar::bar (int m, int n) {
foo* data = new foo[m*n*4];

You just declared a local object with the name 'data', which *hid* the
member with the same name.
}

Now I have a problem with function add, where I should access particular
element in data array of foo's and assign values from parameter, but don't
know exactly how. This doesn't work since it throws segmentation fault:

bar::add (foo S, int i, int j) {
data[(i*j*4)-].a = S.a;
data[(i*j*4)-].b = S.b;

Check the value of 'data' here. And what exactly do the minuses do
after the closing parentheses in the indexing expressions?
}

What's the proper way to do that? I require array of foo's in the bar's
constructor.

If you read the FAQ section 10 carefully, you can avoid the mistakes
like the one you've made.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top