Reputation: 620
I have a project and I have to define an array of arrays of different dimensions (like a triangle) because I am not allowed to use std::vector or other container class. For this, I am using an array of pointers. Normally, I would do this:
int* triangle[n];
for(int i = 0; i < n; i++) {
triangle[i] = new int[i + 1];
for(int j = 0; j <= i; j++) cin >> triangle[i][j];
}
But I must not use dynamic memory! I thought that doing
int* triangle[n];
for(int i = 0; i < n; i++) {
int row[i + 1];
triangle[i] = row;
for(int j = 0; j <= i; j++) cin >> triangle[i][j];
}
would do the trick. But it didn't. Instead, when I iterate over the arrays and print the contents, I get garbage. So, how can I replace a dynamic allocation with a static one?
Upvotes: 0
Views: 448
Reputation: 620
As @BeyelerStudios pointed out in the comments, at the end of the for loop, the memory allocated for the row
array gets freed. When I am trying to print out the contents, I am dereferencing pointers to this freed up memory, so I am getting garbage. Thank you!
Upvotes: 0
Reputation: 5369
So, if you want "array of arrays" simplified, your choice is array linearization. It means that instead of 7 arrays of 10 items each you should declare single array of 70 elements. Then, just change nested indexes with a function that calculates resulting shift in linearized array, and viola!
Here you can find one of such examples: How to map the indexes of a matrix to a 1-dimensional array (C++)?
In case you don't know in advance how long is your array, it may be a tough choice to determine preliminary reservation size (for example, STL containers like vector etc. do the same trick: they allocate a chunk of memory then grow the container until free capacity left, then re-allocate bigger chunk moving the data from old to new buffer, and again, and again, and again...)
Upvotes: 3