c
1#include<stdio.h> 2#include<stdlib.h> 3#include<errno.h> 4#include<string.h> 5#include<ctype.h> 6#include<unistd.h> 7#include <dirent.h> 8#include<sys/types.h> 9#include<sys/stat.h> 10#include<fcntl.h> 11#include<setjmp.h> 12#include<signal.h> 13 14char* gettoken(char** ptr) 15{ 16 if(strlen(*ptr) == 0)return NULL; 17 char *tmp = *ptr; 18 int idx = 0; 19 int first,end; 20 while(tmp[idx]==' '&&idx<strlen(tmp))idx++; 21 first = idx; 22 while((tmp[idx])!=' '&&idx<strlen(tmp))idx++; 23 end = idx; 24 char* token = malloc(sizeof(char)*(end-first)); 25 for(int i = 0;i<end-first;i++)token[i] = tmp[i+first]; 26 *ptr=&tmp[idx]; 27 if(strlen(token)==0)return NULL; 28 return token; 29} 30 31int main(int argc, char* argv[]) 32{ 33 char *s = "I have a dream", *token; 34 35 while ((token = gettoken(&s)) != NULL) 36 { 37 printf("%s\n", token); 38 free(token); 39 } 40 return 0; 41}
このプログラムは与えられた文字列をスペースごとに区切って表示するためのもので、このmain関数では "I" "have" "a" "dream"となるのが望ましいです。
しかし"a"を取り出すときになぜかaaveと表示されます(前回のhaveが由来のようです)。
mallocで"a"を確保する際にはchar型1つ分しか借りていないはずなのですが、なぜかhaveを格納するだけのサイズを確保しているようです。何が良くなかったのか教えていただけるとありがたいです。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/01/11 18:45
2020/01/11 23:07