Reputation: 801
Hey guys I'm trying to initialize a 2D char array but am having trouble.
int size = 300 * 400;
char * frame[3] = malloc(sizeof(char *)*size*3);
Gives m: error: invalid initializer
.
So I tried:
int size = 300 * 400;
char frame[3][size] = malloc(sizeof(char *)*size*3);
But then I get error: variable-sized object may not be initialized
?
Any ideas how I can initialize an array of size 300*400 with 3 rows?
Thanks.
Upvotes: 0
Views: 1264
Reputation: 38173
You can try:
int size = 300 * 400;
const int rows_number = 3;
char* frame[ rows_number ]; // crate array with 3 elements, each of them `char*`
for( unsigned ii = 0; ii < rows_number; ++ii )
{
// allocate `size` char`s for each "row"
frame[ ii ] = malloc( sizeof(char) * size );
// do not forget to free this memory later
}
Upvotes: 2