Dynamically allocate array of strings

I know I can allocate it this way, on the stack:
1
2
3
4
5
6
char* str[5];

for(i = 0; i < 5; ++i)
{
    str[i] = new char[STR_SIZE];
}


But if I want to allocate array size through 'new', what's the syntax for that?

I thought this might work, but it gives error: "Initialization with {...} expected for aggregate object"

 
char* newString[] = new char[5][ARRAYSIZE];


Thanks!
OP wrote:
I know I can allocate it this way, on the stack:
1
2
3
4
5
6
char* str[5];

for(i = 0; i < 5; ++i)
{
    str[i] = new char[STR_SIZE];
}

Only part of it is allocated on the stack.

As for the error. You are only allowed to use new or new[] not new[][]. So You have to iterate over and use new[]. Also you should use strings not c-strings imo. Also when you use raw pointers like this you are going to have to use delete after each new and delete[] after each new[]. I prefer to use a container such as std::vector or smart pointers such as std::unique_pointer
You are only allowed to use new or new[] not new[][]. So You have to iterate over and use new[].


Does this mean there is no way to allocate the entire array of strings on heap?

In this specific problem, I am trying to solve a problem without using STL libraries.

Thanks!
Does this mean there is no way to allocate the entire array of strings on heap?
to allocate on the heap is to use the keyword new. That is the only way to make a dynamic array.

Basically to create a dynamic 2d array you need to do something like:
1
2
3
4
5
6
7
8
9
10
11
12
13
type **name = new type[rows];
for(int i = 0; i < rows; ++i)
{
    type[i] = new type[column];
}

//some time later to ensure no memory leaks
for(int i = 0; i < rows; ++i)
{
    delete [] type[i];
}

delete [] type;


*typo
Last edited on
I suppose the last delete corresponds to the first new - basically number of strings allocated.

Shouldn't it be

 
delete [] type


The reason being, since name is a 2D array, one dimension (which is column - length of each string) is de-allocated using the delete [] inside for loop and the other dimension (which is row - number of strings) should also be de-allocated using delete[].
Shouldn't it be
delete [] type
Yes, you are correct.
Another way is like this:

1
2
3
4
5
6
7
8
9
10
11
12
int *data = new int [width * height];
int *row = new int *[height];

int i;
for(i = 0; i < height; i++)
   row[i] = &data[width * i];

// to write an x,y position:
*(row[y] + x) = 5;

// to read an x,y position:
var = *(row[y] + x);


Can make a nice 2D array class pretty easy this way.

Topic archived. No new replies allowed.