【发布时间】:2011-08-26 15:57:37
【问题描述】:
我对 C 语言相当陌生,并开始编写一个小型库,该库具有获取字符串长度、反转字符串、将 char 缓冲区中的二进制数据转换为 int 和 short 的功能。只是为了教育和更好地掌握 string.h 等中已经提供的低级功能。
问题是我遇到的错误在某种程度上是随机的。我有 4 个功能:
-
getStringLength(获取字符串的长度) -
reverseString(使用 XOR 替换反转字符串并使用 getStringLength 获取长度) -
charsToUShort(将具有两个字节(不包括空项)二进制数据的 char 数组指针转换为无符号短整数) -
charsToUInt(将二进制数据的四个字节(不包括空项)的 char 数组指针转换为无符号整数)
当我在主函数中测试所有这些函数时,基本上会出现问题。当使用所有函数时,reverseString 中的迭代器将从0 到length / 2 设置为32767。所以基本上当字符串的反转被迭代时,循环甚至不会开始,因为迭代器是32767。尽管它被初始化为 0。如果我只使用其中的 3 个作为函数,例如,如果我删除 charsToUInt 我的主要函数,它就会按预期工作。
主要问题
- 您对解决此类问题有什么建议?
- 也非常欢迎所有其他建议!
容易出错的代码说明
getStringLength:
unsigned int getStringLength(char *str){
unsigned int i = 0;
while(str[i]){
i++;
}
return i;
}
reverseString:
void reverseString(char *str){
int i, m = 0;
unsigned int l = getStringLength(str);
m = l >> 1;
while(i < m){
str[i] ^= str[l - 1];
str[l - 1] ^= str[i];
str[i] ^= str[l - 1];
i++;
l--;
}
}
charsToUShort:
unsigned short charsToUShort(char *str){
unsigned int l = getStringLength(str);
unsigned short result = 0;
if(l != 2){
return 0;
}else{
result |= str[0] << 8;
result |= str[1] << 0;
return result;
}
}
charsToUInt:
unsigned int charsToUInt(char *str){
unsigned int l = getStringLength(str);
unsigned int result = 0;
if(l != 4){
return 0;
}else{
result |= str[0] << 24;
result |= str[1] << 16;
result |= str[2] << 8;
result |= str[3] << 0;
return result;
}
}
澄清测试输出
这是测试的输出错误结果:
0: reverseString failed! Expected value: 'olleH', actual value: 'Hello'
1: charsToUShort passed! Expected value: '0x6261', actual value: '0x6261'
2: charsToUInt passed! Expected value: '0x62616364', actual value: '0x62616364'
这是预期的结果:
0: reverseString passed! Expected value: 'olleH', actual value: 'olleH'
1: charsToUShort passed! Expected value: '0x6261', actual value: '0x6261'
2: charsToUInt passed! Expected value: '0x62616364', actual value: '0x62616364'
【问题讨论】:
-
我个人建议使用
uint16_t和uint32_t而不是short和int,因为尺寸更明显,而且不会因架构而改变。 -
@shart 感谢您的建议!我将研究 uint16_t 和 uint32_t 并阅读架构中类型大小的变化。
标签: c pointers memory-management undefined-behavior chars