简体   繁体   中英

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

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.

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.

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.

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM