beam = new (beams*) [numElements]

Ok, so this is a really basic question (or at least I think so).

What I'm trying to do is to use the default constructor to create an array of type beams that is numElements long.

I'm using gcc-g++ version 4.1.2 and I'm getting the following error:

error: array bound forbidden after parenthesized type-id
note: try removing the parentheses around the type-id

I've learned that this syntax was allowed in gcc-g++ versions prior to 4.0, but was then disallowed (for what ever reason).

Following the hint from the compiler actually makes the code compile, but I get an error at runt time. I guess this is due to that the statement is enterpreted as something else when leaving out the parantheses and this is where I get confused.

How can I write an equivalent expression without using the parantheses?

Thanks in advance
Rickard


Last edited on
If you want to create some beams, then you want to new some beams. You do not want to new beams*

The proper way to do it is like so:

 
beams* beam = new beams[numElements];
Yes, but wat I want is an array of beams, compare int*[numElements]
Yes. new beams[numElements]; gives you an array of beams.

new beams*[numElements]; would give you an array of pointers, not beams (you might do this if you want a 2D "nested new" array - though I don't recommend that approach)
Ok, maybe that's what I want then!?
I'm not the author of the code, which makes it so much harder to debug it...
From your description, it does not sound like you want a 2D array.

A 1D array would look like this:

1
2
3
4
5
6
7
8
// creation
beams* beam = new beams[numElements];

// accessing a single element
beam[x].whatever();

// cleanup
delete[] beam;


A 2D array would look like this:
1
2
3
4
5
6
7
8
9
10
11
12
// creation
beams** beam = new beams*[height];
for(int i = 0; i < height; ++i)
  beam[i] = new beams[width];

// accessing a single element
beam[y][x].whatever();

// cleanup
for(int i = 0; i < height; ++i)
  delete[] beam[i];
delete[] beam;
Ok, now the following code:

Beam* beams = new Beam[numBeams];

generates the following output during compilation

773: error: conflicting declaration âBeam* beamsâ
644: error: âbeamsâ has a previous declaration as âBeam** beamsâ

Line 644 reads
Beam **beams = NULL;


Okay, "beams" already was declared as a Beam** (pointer to a pointer), so it looks like they did want a 2D array.

It's really hard to know what they want without seeing the code though.
Topic archived. No new replies allowed.