各文字列がコンパイル時に既知の同じサイズである場合、たとえば100である場合は、次のように実行できます。
typedef char cstring[100]; //cstring is a new type which is
//a char array of size 100
cstring *arrstring = malloc (1000 * sizeof (cstring));
int i;
for( i = 0 ; i < 1000 ; ++i)
strcpy(arrstring[i], "some string of size less than or equal to 100");
for( i = 0 ; i < 1000 ; ++i)
printf("%s\n", arrstring[i]);
デモ: http: //ideone.com/oNA30
1. @Eregrithがコメントで指摘したように、コードをCとしてコンパイルする場合、キャストは推奨されません。ただし、C ++としてコンパイルする場合は、記述する必要があります(cstring*)malloc (1000 * sizeof (cstring))
が、C ++では、そのようなコードを記述しないようにする必要があります。そもそも。std::vector<std::string>
この投稿の下部で説明されているように、C++のより良い代替手段はです。
コンパイル時に各文字列のサイズがわからない場合、または各文字列のサイズが同じでない場合は、次のように実行できます。
char **arrstring = malloc(sizeof(char*) * 1000); //1000 strings!
int i;
for(i = 0 ; i < 1000; ++i)
arrstring[i] = (char*) malloc(sizeof(char) * sizeOfString);
sizeOfString
1000本の弦すべてに同じサイズを想定しています。サイズが異なる場合は、反復ごとに異なる値を渡す必要があります。たとえば、次のようになります。
for(i = 0 ; i < 1000; ++i)
arrstring[i] = malloc(sizeof(char) * sizeOfEachString[i]);
それがお役に立てば幸いです。また、残りは自分でできることを願っています。
ちなみに、C ++では、これを行うべきではありません。
string* arrayOfString = new string[10]; //avoid new as much as possible!
代わりに、これを行う必要があります。
std::vector<std::string> strings;
strings.reserve(10);