Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c++ > #14792

Re: Accessing array member created by another structure constructor

From Victor Bazarov <v.bazarov@comcast.invalid>
Newsgroups comp.lang.c++
Subject Re: Accessing array member created by another structure constructor
Date 2012-03-06 16:56 -0500
Organization A noiseless patient Spider
Message-ID <jj616l$qrf$1@dont-email.me> (permalink)
References <XnsA00EE71F2367Dbubbachipsetone@130.133.4.11>

Show all headers | View raw


On 3/6/2012 4:43 PM, Bubba wrote:
> 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
-- 
I do not respond to top-posted replies, please don't ask

Back to comp.lang.c++ | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

Accessing array member created by another structure constructor Bubba <nickname@banelli.biz.invalid> - 2012-03-06 21:43 +0000
  Re: Accessing array member created by another structure constructor Victor Bazarov <v.bazarov@comcast.invalid> - 2012-03-06 16:56 -0500
    Re: Accessing array member created by another structure constructor Bubba <nickname@banelli.biz.invalid> - 2012-03-09 09:47 +0000

csiph-web