【问题标题】:Incompatible Type Error不兼容的类型错误
【发布时间】:2014-03-20 17:52:35
【问题描述】:
main()
{
FILE *fin;
char line[50];
char exp[SIZE];
fin=fopen("prefix.txt","r");

if(fin==NULL)
{
     printf("\nFile Cannot be Opened\n");              
}
else
{
        printf("\nfile opened\n");

       while(fgets(line, sizeof(line), fin)!=NULL)
       {
              sscanf(line, "%s", exp);

              exp=delete_spaces(exp);
       }    
}
fclose(fin);
getch();   
}

char delete_spaces(char a[])
{
   int l,k=0,i=0;
   l=strlen(a);

   while(i<l)
   {
        if(a[i]==' ')
        i++ 
        else
        a[k++]=a[i++];    
   } 
   return a;    
}

编译此程序后,我收到错误“兼容性类型错误” 在包含“exp=delete_spaces(exp);”的行中我不知道如何删除它。 数组传递有问题吗?

【问题讨论】:

    标签: c arrays string incompatibletypeerror


    【解决方案1】:

    在这里,您在调用 delete_spaces(exp) 时将数组地址传递给 delete_spaces(char a[]),因此您不需要获取返回值并分配回为

    exp=delete_spaces(exp);
    

    改为将函数定义改为,

    void delete_spaces(char a[]);
    

    和函数调用

    delete_spaces(exp);
    

    并且还将函数的定义或原型放在main()之前。并从 delete_spaces() 定义中删除 return 语句。

    delete_spaces() 的代码是

    void delete_spaces( char a[])
    {
        int l,k=0,i=0;
       l=strlen(a);
    
       while(i<l)
       {
            if(a[i]==' ')
            i++; 
            else
            a[k++]=a[i++];    
       } 
       a[k]='\0';
    }
    

    【讨论】:

    • @user39495 好的。我做了改变来回答检查它。它可能会有所帮助
    • 是的,它正在工作,但更早为什么它不工作
    • @user39495 它不起作用,因为 exp 是一个 char 数组,并且在 C 中 char[] 和 char * 不一样。阅读this 或相关问题以获得一些想法。
    • 上面的函数delete_spaces采用任意数组并删除字符之间的空格,上面的代码会起作用吗???
    • @user39495 是的,但添加了 [k]='\0'。检查我添加到答案的代码。它可能会帮助你
    猜你喜欢
    • 1970-01-01
    • 2013-09-23
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    • 2012-10-19
    • 1970-01-01
    相关资源
    最近更新 更多