【问题标题】:both are char but i get, invalid conversion from `char' to `char*' [closed]两者都是 char 但我明白了,从 `char' 到 `char*' 的无效转换 [关闭]
【发布时间】:2014-05-19 21:08:40
【问题描述】:

我正在编写一个只使用 C 的程序,我是一名学生,只有 5 个月的培训。它将打开一个文件,将行存储为字符串,计算我使用的数组中有多少个字符串,然后关闭文件。这是我写的函数。

char animalsarray[100][100], xstring='x';
int numlines1;

void preload(){
  int j; 
  strcpy(animalfile,"animals.txt.");
  animals=fopen(animalfile,"r");
  if(animals==NULL){
    printf("ERROR: animals.txt not found!");
    exit(13);
}
for(j=0;j<100;j++){
    strcpy(xstring, animalsarray[j][0]);
}
j=0;
while(sscanf(animalsarray[j][0],100,animals)!= EOF){
    j++;
}
for(j=0;j==100;j++){
    if(animalsarray[j][0]!='x'){
        numlines1++;
    }
}
fclose(animals);

} 我遇到的问题是这个

错误:来自char' to char*'的无效转换

错误:初始化 `char* strcpy(char*, const char*)' 的参数 1

错误:来自char' to const char*'的无效转换

错误:正在初始化 `char* strcpy(char*, const char*)' 的参数 2

将单个字符放入所有字符串有什么问题吗?

【问题讨论】:

  • 您能告诉我们错误发生在哪一行,并在您的代码中标记该行吗?
  • 我推测这是他拥有的每个地方animalsarray[j][0]xstring
  • 你见过xstring的类型吗?它不是一个 char* 而是一个简单的 char。另外,我引用@KerrekSB。请提供更多信息,因为我们不是读心者:)
  • strcpy(xstring, animalsarray[j][0]); -> animalsarray[j][0]=xstring;,
  • while(sscanf(animalsarray[j][0],100,animals)!= EOF){ --> while(fgets(animalsarray[j],100,animals)!= NULL){

标签: c arrays string


【解决方案1】:

您不仅混淆了strcpy 中的顺序或参数(它是目标,然后是源,因此strcpy(xstring, animalsarray[j][0]); 会颠倒它的参数),您还将charpointer-to-char 混淆。

xstring 是一个字符,而您正试图将其用作字符串。

如果要将数组的所有元素设置为'x' 字符,请尝试改用memset

for(j=0;j<100;j++){
    memset(&animalsarray[j][0], 100, 'x');
}

虽然这不会将数组的最后一个字符设置为'\0',但您没有以 0 结尾的字符串。为此,请在 memset(...); 之后添加 animalsarray[j][99] = '\0';

如果您确实想将xstring 用作以0 结尾的字符串,则必须对其进行初始化:

*xstring="x";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 2017-03-19
    • 1970-01-01
    相关资源
    最近更新 更多