0

文字列をトークン化し、最初の 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* として) ?

また、私のコードに関する一般的なアドバイスにも興味があります。

4

1 に答える 1

0

メモリ割り当てにいくつかのエラーがあります。例:

char **result=malloc(n*sizeof(char*));
char *s=malloc(sizeof(char*)*10);

これらは次のようになります。

char **result=malloc(n*sizeof(char)*MAX_TOKEN_LENGTH);
char *s=(char *)malloc(sizeof(char)*strlen(str) + 1);

また、この状態を修正する必要があります:

while( result[i] != NULL )

n 個のトークンが生成されたら停止する必要があります。

while( (result[i] != NULL) && (i < n)  )

これが私があなたの関数で試したことです:

#include<string.h>

#define MAX_TOKEN_LENGTH 100

char **tokenize(char *str,const int n){
  char delims[] = " \t,:";
  char **result=malloc(n*sizeof(char)*MAX_TOKEN_LENGTH);
  int i=0;
  char *s=(char *)malloc(sizeof(char)*strlen(str) + 1);
  strcpy(s,str);
  result[i] = strtok(s, delims );
  while( (result[i] != NULL) && (i < n)  ) {
  //printf( "\nresult is \"%s\"", result[i]);
  i++;
  result[i] = strtok( NULL, delims );
  }
  printf("\n");
  return result;
}

int main(){
char **result;
int i;
int number_of_tokens = 4;
result = tokenize("hi i am: abhipranay,a\tchauhan",number_of_tokens);
for(i=0;i < number_of_tokens; i++){
    printf("%s\n",(result[i]));
}
return 0;
}
于 2013-10-01T13:34:52.900 に答える