0

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.

2
  • Not all C/C++ compilers support declaring an array using a variable size. Commented Apr 23, 2013 at 9:27
  • Are you trying to allocate an array of 3 character pointers to buffers of 120000 characters ? What is the point of the 300 * 400 - some kind of array in an array? Commented Apr 23, 2013 at 9:29

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

@H2CO3 - I know, but it's compile time and it's more readable (at least to me)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.