【问题标题】:Error while passing an array to a function将数组传递给函数时出错
【发布时间】:2015-04-02 07:56:27
【问题描述】:

我试图通过值传递一个数组,或者更确切地说是一个指向函数 BinaryToHex 的数组的指针。但是我一直收到错误“函数 BinaryToHex 的类型冲突”。

这是程序的相关部分。

char *ConvertCodeToHex(char code[16])     
{                  
    char nibble[4];   
    char hexvalue[4];   
    int i;int j,k = 0;      

    for(i=0; code[i] != '\0'; i++)      
       {   
          if((i+5)%4 == 0)           
            {   
                nibble[j] = '\0';
                j = 0;              
                hexvalue[k] = BinaryToHex(nibble);
                k++;
            }
            nibble[j] = code[i];
            j++;
       }
    strncpy(finalhex, hexvalue, 4); //finalhex is a global character array
    return finalhex;
}
char BinaryToHex(char b[4])       //The error is caught in this line of code.
{
    int temp = 0,i; char buffer;
    for(i=4; i >= 0; i-- )   
        {
            int k = b[i]-='0';
            temp +=  k*pow(2,i);
        }
//Converting decimal to hex.
    if (temp == 10)
        return 'A';
    else if (temp == 11)
        return 'B';
    else if (temp == 12)
        return 'C';
    else if (temp == 13)
        return 'D';
    else if (temp == 14)
        return 'E';
    else if (temp == 15)
        return 'F';
    else
        return (char)(((int)'0')+ temp);

}

【问题讨论】:

标签: c arrays argument-passing


【解决方案1】:

在调用它之前你需要函数声明,所以在顶部添加额外的行,例如

char BinaryToHex(char b[4]);
char *ConvertCodeToHex(char code[16])     
{                  
    char nibble[4];   
    char hexvalue[4];   
    int i;int j,k = 0;      

    for(i=0; code[i] != '\0'; i++)      
       {   
          if((i+5)%4 == 0)           
            {   
                nibble[j] = '\0';
                j = 0;              
                hexvalue[k] = BinaryToHex(nibble);
                k++;
            }
            nibble[j] = code[i];
            j++;
       }
    strncpy(finalhex, hexvalue, 4); //finalhex is a global character array
    return finalhex;
}    

【讨论】:

  • 谢谢!这为我节省了很多时间。
【解决方案2】:

您需要在ConvertCodeToHex() 之前添加一个函数前向声明为char BinaryToHex(char b[4]);。否则,当从ConvertCodeToHex() 调用BinaryToHex() 时,编译器将不知道函数描述。

【讨论】:

  • 谢谢你的回答:)
【解决方案3】:

您不需要在函数定义中传递数组索引。只需简单地编写 char BinaryToHex(char b[])。看看它会起作用。

【讨论】:

  • 将它作为 char b[4] 传递也可以。不过,这不是错误所在。
猜你喜欢
  • 1970-01-01
  • 2010-11-19
  • 1970-01-01
  • 2020-12-13
  • 1970-01-01
  • 2020-06-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多