Reputation: 495
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
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
Reputation: 1198
Try this:
int main()
{
char** a = new char* [100];
delete []a;
return 0;
}
Upvotes: -2
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
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