【发布时间】:2013-11-24 13:23:36
【问题描述】:
作为旨在存储字典并根据它替换单词的程序的一部分,我编写了一个函数,该函数基本上将(使用strtok)一个字符串拆分为它的单词(由空格分隔),并将存储每个单词转换成字符串数组。
代码如下:
void StoreArr(char * original,char ** dest)
{
int i=0;
char * token =strtok(original, " ");
dest[i]=malloc(sizeof(token));
strcpy(dest[i],token);
++i;
while(token!=NULL)
{
dest[i]=malloc(sizeof(token));
strcpy(dest[i],token);
printf("%s",token);
token =strtok(NULL, " ");
++i;
}
}
我传递了以下变量:
char * File = "";
File=malloc(Length(Text)*(sizeof(char)));
char ** Destination[Count(' ',File)];
destination 的长度是单词的数量。
一旦程序运行,它会自行终止而不显示文本
使用StoreArr(File,Destination);调用它
编辑:
int Length(FILE * file)
{
long result;
long origPos = ftell(file);//original start position of file
fseek(file, 0, SEEK_END);//move to end of file
result = ftell(file);//return value at end
fseek(file, origPos, SEEK_SET);//rewind to beginning
return result;
}
int Count(char a,char * b)
{
int i=0;
int count=0;
while(b[i]!='\0')
{
if(b[i]==a || b[i]=='\n')
++count;
++i;
}
return count+1;
}
?我收到警告“从不兼容的指针类型传递 'StoreArr' 的参数 1,2 [默认启用]” 提前致谢。
ps:Breaking down string and storing it in array
上一篇文章的代码和我的一样,但是我的不行。我怀疑这两行有问题,我不知道为什么:
dest[i]=malloc(sizeof(token));
strcpy(dest[i],token);
【问题讨论】:
-
启用更多警告(如果您还没有)。警告经常表明你正在做一些你不应该做的事情。
-
另外,请发布一个完整示例,解释
Length和Count是什么。最好是SSCCE。 -
最后一件事,在
strtok不返回NULL时循环可能会更好。例如。while (token != NULL) { ... } -
我添加了 2 个函数,并将其更改为 while(即使在这种情况下它不相关)。还有其他解决方案吗?我收到警告“传递 'StoreArr 的参数 2 ' 来自不兼容的指针类型 [默认启用]"
-
我收到一条警告“从不兼容的指针类型传递 'StoreArr' 的参数 1,2 [默认启用]”