C语言 传递参数从整数生成指针而不进行强制转换



我有一个名为token2char的函数,它以一个名为token的字符数组传递,数组大小为1024。我正在遍历每个字符,查找它是十六进制(假设十六进制值的长度始终为 2,例如 0xFF(还是 0 到 255 之间的整数。这些值分别hexdec移动到新的 char 数组中,然后将其传递给另一个将其转换为 ASCII 的函数。下面是我的十六进制代码的截断版本。

void token2char(char token[1024]){
// Iterate through each character in token
for (int i = 0; i < maxInputLength; i = i + 1){
// Ignore spaces, move to next char in token
if (token[i] == ' '){}
// Is Hex?
else if (token[i] == '0' && (token[i+1] == 'x' || token[i+1] == 'X')){
char hex[4];
strcpy(hex, token[i,i+1,i+2,i+3]);
hexConv(hex);
}
}
}

strcpy 抛出了标题中定义的错误,但我不确定为什么。我尝试在 strcpy 中调用 &token 或 *token 无济于事。

token[i,i+1,i+2,i+3]

被解释为

token[i+3]

因为逗号是运算符。

你应该使用

strncpy(hex, &token[i], 4);

memcpy(hex, &token[i], 4);

相反。

发布的代码距离编译还有很长的路要走。 即除了不正确的参数之外还有很多问题要strcpy()

以下建议的代码:

  1. 警告:不处理极端情况
  2. 警告:不处理十进制数
  3. 消除不必要的数据复制
  4. 干净地编译
  5. 避免"魔术"数字
  6. 修改 'hexConv((' 以返回消耗的字符数
  7. 使用系统头文件:"ctype.h"设施"isspace((">

现在,建议的代码:

#include <ctype.h>
// avoid 'magic' numbers
#define MAX_INPUT_LENGTH 1024

//prototypes
void token2char( char * );
int  hexConv( char * );  // returns num of chars used

void token2char( char token[ MAX_INPUT_LENGTH ] )
{
// Iterate through each character in token
for ( int i = 0; i < MAX_INPUT_LENGTH; i++ )
{
// Ignore spaces, move to next char in token
if ( !isspace( token[i] ) )
{
if ( token[i] == '0' 
&& (token[i+1] == 'x' || token[i+1] == 'X') )
{
int charsUsed = hexConv( &token[i] );
i += charsUsed;
}
}
}
}

最新更新