icedTea
icedTea

Reputation: 495

How do I allocate memory for a pointer to an array of char *?

Could someone please explain how to correctly allocate memory for for a pointer to an array of pointer of characters in c? For example:

char *(*t)[];

I try to do it like this:

*t = malloc( 5 * sizeof(char*));

This gives me a compile error:

error: invalid use of array with unspecified bounds

Any assistance on this would be great! Thanks

Upvotes: 1

Views: 4110

Answers (4)

Jan S
Jan S

Reputation: 1837

What you can do is:

char **t = (char**)malloc( <no of elements> * sizeof(char*));

That allocates the array of pointers.

for (i = 0 ; i< <no of elements> ; i++)
{
    t[i] = (char*)malloc( <length of text> * sizeof(char));
}

That allocates memory for the text that each element of the array points to.

Upvotes: 5

skimobear
skimobear

Reputation: 1198

Try this:

int main()
{
    char** a = new char* [100];
    delete []a;
    return 0;
}

Upvotes: -2

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215261

When people say "a pointer to an array of X", usually they really mean a pointer to the first element of an array of X. Pointer-to-array types are very clunky to use in C, and usually only come up in multi-dimensional array usage.

With that said, the type you want is simply char **:

char **t = malloc(num_elems * sizeof *t);

Using a pointer-to-array type, it would look like:

char *(*t)[num_elems] = malloc(sizeof *t);

Note that this will be a C99 variable-length array type unless num_elems is an integer constant expression in the formal sense of the term.

Upvotes: 2

rubixibuc
rubixibuc

Reputation: 7397

Well it depends how you want it to be allocated, but here is one way.

char** myPointer = malloc(sizeof(char *) * number_Of_char_pointers)
int i;
for(i = 0; i <  number_Of_char_pointers; i++)
{
     myPointer[i] = malloc(sizeof(char) * number_of_chars);
}

something to note is that myPointer[i] is almost exactly identical to saying *(myPointer + i), when being used to dereference a variable, not during initialization.

Upvotes: 0

Related Questions