Strcpy复制到其他char数组

时间:2017-11-03 17:05:54

标签: c

我正在尝试将十六进制转换为字符串,但是当使用strcpy然后将其追加到另一个变量时,我面临着奇怪的问题。

以下是我的代码

int hex_to_int(char c) {
int first = c / 16 - 3;
int second = c % 16;
int result = first * 10 + second;
if (result > 9) result--;
return result;
}

int hex_to_ascii(char c, char d) {
int high = hex_to_int(c) * 16;
int low = hex_to_int(d);
return high + low;
}


void hexToString(char st[16], int length, char string[16]) {
char buf = 0;
char tempHTS[16] = {""};
char tempHTS1[16] = {""};

for (int i = 0; i < length; ++i) {
    if (i % 2 != 0) {
        sprintf(tempHTS, "%c", hex_to_ascii(buf, st[i]));
        strcat(tempHTS1, tempHTS);
    } else {
        buf = st[i];
    }
}
strcpy(string,tempHTS1);
}

void decodeToHex(unsigned char readingreg[16], int length, char hexString[16]) {
char tempDTH[16];
char tempDTH1[16]={""};

for (int j = 0; j < length; ++j) {
    sprintf(tempDTH, "%x", readingreg[j]);
    strcat(tempDTH1, tempDTH);
}
strcpy(hexString,tempDTH1);
}

int main() {
unsigned char readingreg[9];
readingreg[0] = 0x74;
readingreg[1] = 0x68;
readingreg[2] = 0x69;
readingreg[3] = 0x73;
readingreg[4] = 0x20;
readingreg[5] = 0x74;
readingreg[6] = 0x65;
readingreg[7] = 0x73;
readingreg[8] = 0x74;
char hexString[16];
char actualString[16];

decodeToHex(readingreg, sizeof(readingreg), hexString);
hexToString(hexString, (int) strlen(hexString), actualString);

printf("\n%s\n", actualString);
printf("\n%s\n", hexString);

return 0;
}

以下是输出

这个测试

7468697320746573此测试

在第二次打印&#34;此测试&#34;获取自动附加到十六进制字符串。 我没理由。请帮忙。

提前致谢。

1 个答案:

答案 0 :(得分:0)

readingreg有9个字节,这意味着您至少需要9*2+1 = 19个字符来存储该数据的十六进制字符串(每个字节为2个,空终止符为1个)。 hexString只有16个字节,所以你最终写出越界,导致未定义的行为。