Reputation: 1662
I have a bunch of multidimensional arrays in C.
They look like this: (they are chars because ints in c take 4 bytes of memory instead of 1 byte for chars they are not used as strings)
char booting[96][25] = {{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},{0x00,0x18,0x18,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},{0x06,0x7e,0x7c,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00} ... .. ..
They are 2400 chars long and I have many of them. If I do this with a couple of them it works ok and i can acces them with:
char current_pixel = booting[34][2];
But after 9 or 10 arrays defined like this although it compiles ok, at runtime I get a StackOverflow error.
Question is: What is a better way to assign them on heap and to still keep accessing them like they are normal arrays on stack?
ps. I have looked around but still did not find exactly what I was looking for. Thanks for bearing with me!
Upvotes: 1
Views: 472
Reputation: 21773
vector< vector< char > > booting(y_size, vector< char >(x_size, starting_value));
Access this way (x and y may be opposite to what you expect)
for (int y = 0; y < y_size; y++)
{
for (int x = 0; x < x_size; x++)
{
cout << booting[y][x];
}
}
Upvotes: 1
Reputation:
Either declare them as a global variable or as static
so that they don't take up stack space:
static char booting[96][25] = { { 0x00, ... }, ... };
Or use malloc()
for dynamic memory allocation:
char (*booting)[25] = malloc(96 * sizeof(*booting));
Upvotes: 5