In C++ I can allocate an array of strings (say 10 strings) very easily as:
string* arrayOfString = new string[10];
however I don’t know how to do it in ANSI C. I tried:
char** arrayOfString = (*(char[1000])) malloc (sizeof (*(char[1000])));
But the compiler (MinGW 3.4.5) keeps saying that it is “Syntax error”.
How to do it right?
Thanks.
If each string is of same size which is known at compile time, say it is 100, then you can do this1:
Demo : http://ideone.com/oNA30
1. Note that as @Eregrith pointed out in the comment that cast is not advised if you compile your code as C. However, if you compile it as C++, then you need to write
(cstring*)malloc (1000 * sizeof (cstring))but then in C++, you should avoid writing such code in the first place. A better alternative in C++ is,std::vector<std::string>as explained at the bottom of this post.If the size of each string is not known at compile time, or each string is not of same size, then you can do this:
I’m assuming same size
sizeOfStringfor all 1000 strings. If they’re different size, then you’ve to pass different value in each iteration, something like this:I hope that helps you, and I also hope you can do the rest yourself.
By the way, in C++, you should not do this:
Instead, you should do this: