【问题标题】:ASCII to HEX conversion in c programming error [duplicate]c编程错误中的ASCII到HEX转换[重复]
【发布时间】:2021-09-23 02:53:36
【问题描述】:

当我尝试编译代码时,出现如下错误

main.c:12:15:错误:“ascii_to_hex”的类型冲突 unsigned char ascii_to_hex(unsigned char* buf)


#include <stdio.h>
#include <stdlib.h>
int main()
{
    
unsigned char str[] = {0x32, 0x35, 0x34, 0x035};
ascii_to_hex(str);

    return 0;
}

unsigned char ascii_to_hex(unsigned char* buf)
{
   unsigned char hundred, ten, unit, value;

   hundred = (*buf-0x30)*100;
   ten = (*(buf + 1)-0x30)*10;
   unit = *(buf+2)-0x30;     

   value = (hundred + ten + unit);
   printf("\nValue: %#04x \n", value);

   return value; 
}

我在这里做错了什么?

【问题讨论】:

  • strunsigned char[4],但 ascii_to_hex 需要 unsigned char*。改为通过&amp;str[0]
  • 该错误应该更多,告诉您ascii_to_hex 函数有一个隐式声明。将函数移到main之上或在调用函数之前声明一个函数原型。
  • @Raildex:这是不正确的。这部分代码没有任何问题,只要在使用前声明函数,它就可以正常工作。
  • 谢谢大家,它现在没有任何修改就可以工作了,我把函数定义移到了main()上面。

标签: c hex ascii


【解决方案1】:

您在声明它之前使用ascii_to_hex,因此编译器推断它具有函数的“默认”签名。我忘记了具体是什么,[编辑:显然是

int ascii_to_hex()

--我查过了],但不管是什么,都不是

unsigned char ascii_to_hex(unsigned char* buf)

编译器告诉你的是它推断的函数签名与它后来遇到的签名不匹配。这在 gcc 的输出中很多更清楚:

cc     program.c   -o program
program.c: In function ‘main’:
program.c:11:1: warning: implicit declaration of function ‘ascii_to_hex’ [-Wimplicit-function-declaration]
   11 | ascii_to_hex(str);
      | ^~~~~~~~~~~~
program.c: At top level:
program.c:16:15: error: conflicting types for ‘ascii_to_hex’
   16 | unsigned char ascii_to_hex(unsigned char* buf)
      |               ^~~~~~~~~~~~
program.c:11:1: note: previous implicit declaration of ‘ascii_to_hex’ was here
   11 | ascii_to_hex(str);
      | ^~~~~~~~~~~~
make: *** [<builtin>: program] Error 1

因此您可能希望考虑使用更好的编译器或 IDE,或者关闭开发管道中抑制大部分相关信息的任何部分。

要解决此问题,您需要将函数定义移到 main 的定义之上,或者为函数提供一个原型,以便编译器在调用它时知道它的签名。

【讨论】:

  • 是的,你是对的!!我将函数定义移到了 main() 上面,没有做任何修改,它运行良好。
猜你喜欢
  • 2015-11-06
  • 2012-03-01
  • 1970-01-01
  • 2015-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-09
  • 1970-01-01
相关资源
最近更新 更多