TatianaCooper
TatianaCooper

Reputation: 155

Incomplete type compilation error with malloc memory allocation

static char st[][8192];
void foo ( int tab_size){
    st = (char**) malloc ((tab_size+1)*sizeof(char)*8192);
}

I receive the compilation error in "malloc" line that st has incomplete type. What is wrong? Thanks.

Upvotes: 0

Views: 1295

Answers (3)

John Bode
John Bode

Reputation: 123458

Since you don't specify the size of the inner dimension for st, the compiler doesn't know how big it needs to be; hence the type is incomplete, and you never complete it before the malloc call.

Since it looks like your intent is to allocate st dynamically, go with Oli's advice and declare it as a pointer to an 8192-element array of char:

static char (*st)[8192];

and rewrite your malloc statement as

st = malloc(sizeof *st * (tab_size+1));

sizeof *st == sizeof (char [8192]) == 8192. This form is a bit cleaner and easier to read. Note also that in C, you don't have to cast the result of malloc (unless you're using a pre-C89 implementation, in which case, I'm sorry), and the practice is discouraged.

This will allocate enough space to hold tab_size + 1 arrays of 8192 characters each.

It is only within the context of a function parameter declaration that T a[] declares a as a pointer to T.

Upvotes: 1

Manohar
Manohar

Reputation: 3975

You are confusing two completely different types: an array vs pointer to an array.

static char st[][8192];

declares st to be of type array. It is not a modifiable lvalue and can't be assigned to.

If your intent was to allocate space for an array of integers and assign it to a pointer use the pointer declaration suggested by Oli Charlesworth.

Note that your declaration of st won't allocate space though. if you try something like this, you would get an error..

printf("0x%x\n", st);

Compiler is treating it like a declaration and expects to see the actual definition elsewhere. Its not a definition because you haven't given the value for the array's first dimension.

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272497

Your definition for st is indeed not a complete type.

Try this instead:

static char (*st)[8192];

void foo (int tab_size){
    st = malloc ((tab_size+1)*sizeof(*st));
}

Upvotes: 1

Related Questions