【发布时间】:2014-01-21 12:30:07
【问题描述】:
我试图在动态分配它的同时从用户那里获取输入,然后使用 strtok “拆分”它。
主要问题:
- 我遇到了“a{\300_\377”和“,”的无限循环。
- 为什么我会收到“隐式声明库函数“malloc”/“realoc”类型为 void”的警告
其他不太重要的问题:
3.我想打破,如果输入包括“-1”,我该如何检查?如您所见,如果它为 1,它现在会中断。
4.在 getsWordsArray() 中,我想返回一个指向字符串数组的指针。由于我不知道有多少字符串,我还需要像在 getInput() 中那样动态分配它。 (我不知道每个字符串中有多少个字符)
int main(int argc, const char * argv[])
{
char input = getInput();
getWordsArray(&input);
}
char getInput()
{
char *data,*temp;
data=malloc(sizeof(char));
char c; /* c is the current character */
int i; /* i is the counter */
printf ("\n Enter chars and to finish push new line:\n");
for (i=0;;i++) {
c=getchar(); /* put input character into c */
if (c== '1') // need to find a way to change it to -1
break;
data[i]=c; /* put the character into the data array */
temp=realloc(data,(i+1)*sizeof(char)); /* give the pointer some memory */
if ( temp != NULL ) {
data=temp;
} else {
free(data);
printf("Error allocating memory!\n");
return 0 ;
}
}
printf("list is: %s\n",data); // for checking
return *data;
}
void getWordsArray(char *input)
{
char *token;
char *search = " ,";
token = strtok (input,search);
while (token != NULL ) {
printf("%s\n",token);
token = strtok(NULL,search);
}
}
编辑:
我注意到我忘记了“strtok”命令所以我把它改成了token = strtok(NULL,search);
我仍然在 printf 上得到奇怪的输出:
\327{\300_\377
【问题讨论】:
-
什么是'token = (NULL,search);'
-
糟糕.. 已编辑,谢谢。
标签: c malloc clang realloc strtok