文字列をトークン化し、最初の n 個のトークンを char* の配列として返すことを目的とする関数を作成しました。
最初に、文字列をトークン化する関数がありますが、何も返しません(テストするためだけに):
void tokenize_1(char *str,const int n){
char delims[] = " \t,:";
char *result=NULL;
int i=0;
char *s=malloc(sizeof(char*)*10);
strcpy(s,str);
result = strtok(str, delims );
while( result != NULL ) {
i++;
printf( "\nresult is \"%s\"", result);
result = strtok( NULL, delims );
}
printf("\n");
}
次に、 n char* の配列を返したいと思います:
char **tokenize(char *str,const int n){
char delims[] = " \t,:";
char **result=malloc(n*sizeof(char*));
int i=0;
char *s=malloc(sizeof(char*)*10);
strcpy(s,str);
result[i] = strtok(s, delims );
while( result[i] != NULL ) {
printf( "\nresult is \"%s\"", result[i]);
i++;
result[i] = strtok( NULL, delims );
}
printf("\n");
return result;
}
結果は正しいようです。ただし、メッセージを返して出力しない私のプログラム:
* glibc が検出されました * ./program: 破損した二重リンク リスト
それの何がいけないの ?文字列の配列を返すように最初の関数を変更する方法 (char* として) ?
また、私のコードに関する一般的なアドバイスにも興味があります。