源码如下,是想把一个字符串转成BCD码,问题是:连续调用这函数时虽然给函数的是不同的buf参数,但buf相互之间有影响,比如定义如下变量:
char buf1[10];
char buf2[10];
String2BCD(str, buf1);
String2BCD(str, buf2);
buf2的调用会把buf1的内容也改了,感觉是sscanf的问题,好象内存重叠了,请高手指点,谢谢
void CRevDataDlg::String2BCD(const CString &str, char *buf, int bufSize)
{
ASSERT(str.GetLength() % 2 == 0);
int halfLen = str.GetLength() / 2;
ASSERT(halfLen <= bufSize); char * pStr = new char[str.GetLength() + 1];
strcpy(pStr, str);
for (int i = 0; i < halfLen; i ++){
sscanf(pStr + i * 2, "%02x", &buf[i]);
}
delete [] pStr;
}

解决方案 »

  1.   

    char buf1[10];
    char buf2[10];多分配一个字符
    然后String2BCD第三个参数写上10
      

  2.   

    不好意思,打错了,调用应该是
    String2BCD(str, buf1, 10);
    String2BCD(str, buf2, 10);
    为什么要多分配个字符呢?
      

  3.   

    调试时发现函数中buf[bufSize]后三个字节被修改了,不知道为什么,郁闷中
      

  4.   

    这函数你自己写的?onst CString &str这是做什么用的?
    char * pStr = new char[str.GetLength() + 1];
    strcpy(pStr, str);
    拷贝到pStr做什么?
      

  5.   

    str是个字符串,比如“20060606”
    拷贝过去是想用sscanf,因为CString不支持&str[i]这样的用法
      

  6.   

    想在buf里得到“\x20\x06\x06\x06”的结果
      

  7.   

    找到原因了,fscanf认为buf[i]是个整数,而我要的是个字节,整数是四个字节,所以多覆盖了3个字节。