How to malloc an array of char pointers?
-
Hi Right now I have this: char *files[ 20 ]; I then use my array: files[ i ] = whatever; And it works as I want it to. However I want the size of the array to be dynamic, so i tried: char *files; ... files = ( char * ) malloc( array_size * ( sizeof( char ) ); ...but this doesn't seem to work. What's the correct way to convert "char *files[20]" to something of a dynamic size?
-
Answer:
In C, [] is very similar to *. So, char *files[20] gives you 20 pointers, each to a character or an array of characters. Similarly, char **files gives you a pointer to one or more pointers to one or more characters. So, use this: char **files = (char **)malloc(arraySize*sizeof(char *)); This means that file is a pointer to an array of character pointers. Allocate an array of character pointers. In both the *files[20] and the **files cases, be sure to initialize the 20 or the arraySize pointers.
greg at Yahoo! Answers Visit the source
Related Q & A:
- How to access nested array value?Best solution by stackoverflow.com
- How to post an array of complex objects (that has an array of complex objects) with jQuery?Best solution by Stack Overflow
- How to parse inner array in JSON response with PHP?Best solution by Stack Overflow
- How to pass an Array to AngularJS?Best solution by Stack Overflow
- How to convert from string to char in C++?Best solution by Stack Overflow
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.