Please help me out.

I have an error on the following code.

struct A
{
int *aA;
};

int main()
{
...
...
A b[10];

// allocating memory
b[0].aA = new int [1];
b[1].aA = new int [5];
b[2].aA = new int [10];
...
...
// initialize array of struct.
b[0].aA[1] = {1};
b[1].aA[5] = {1,2,3,4,5};
...
return 0;
}

i got an error in initializing. is it the proper way to do it or I have to do it other way which I don't have any idea.
please help me out guys.
b[0].aA is an array of size 1

so the only element is b[0].aA[0]

so the line

b[0].aA[1] = {1} is accessing past array bounds

closed account (zb0S216C)
Initialization takes place at the same time as the declaration. The array initializations aren't actually initializing anything. In fact those lines are assignment operations. The reason why those line produce errors is because braces are used for array initialization and scopes. Those lines are neither of those.

Any dynamically allocated array cannot be initialized with the initialization list.

PS: I've used initialization quite a lot recently.

Wazzak
so. how can I do it to make it work. can you give me example based on my code.
closed account (zb0S216C)
Sure. The allocations are fine, it's the assignment that's wrong. Here's how you'd go about it normally.

1
2
3
4
5
6
// Using std::memset( ):
std::memset( b[0].aA, 0, ( 1 * sizeof( int ) ) );

// Using a loop.
for( int I( 0 ); I < 5; ++I )
    b[1].aA[I] = ( I + 1 );

std::memset( ) is useful for filling a region of memory with the specified numerical value. It resides within <cstdlib>. For further information, see this link: http://www.cplusplus.com/reference/clibrary/cstring/memset/

Wazzak
Last edited on
Topic archived. No new replies allowed.