我正在使用以下代码创建一个用于测试哈希表的“ key ”(特别是,我正在测试删除项目所需的时间):
void remove_keys()
{
for (int i = 0; i < NUM_ITEMS; i++) {
char temp_key[20];
sprintf((char *)&temp_key, "Key: %d", i);
size_t key_len = strlen(temp_key) + 1;
char *key = malloc(sizeof(char) * (key_len));
sprintf(key, "%s", temp_key); // THIS LINE
htable_item *item = htable_item_search(root, key, key_len);
if (!item) {
printf("Item not found: %s\n", key);
} else {
//printf("Item found: %s - %s\n", key, item->value);
if (!htable_item_delete(root, item)) {
printf("Error while deleting: %s\n", key);
}
}
}
}
在我用注释标记的行中有一个奇怪的行为。我正在使用 sprintf 将“temp_key”的内容复制到“key”。在此之前,我使用 strncpy 将“temp_key”的内容复制到“key”,但此操作得到的结果是这样的(从 XCode 的调试器打印):
Printing description of key:
(char *) key = 0x0000000100103ed0 "Key: 10\xb0\xe7\x03\x01\x10"
而“temp_key”会产生以下输出:
Printing description of temp_key:
(char [20]) temp_key = "Key: 10" {
[0] = 'K'
[1] = 'e'
[2] = 'y'
[3] = ':'
[4] = ' '
[5] = '1'
[6] = '0'
[7] = '\0'
[8] = '\0'
[9] = '\0'
[10] = '\0'
[11] = '\0'
[12] = '\0'
[13] = '\0'
[14] = '\0'
[15] = '\0'
[16] = '\0'
[17] = '\0'
[18] = '\0'
[19] = '\0'
}
哈希表使用 memcmp 来比较 htable_item_search 函数中的键。但是使用 strncpy 有一些项目(例如“Key:10”)在使用 sprintf 时找不到,但它工作得很好。那么为什么会出现这种差异呢?
最佳答案
来自http://www.cplusplus.com/reference/clibrary/cstring/strncpy/
如果源比 num 长,则不会在目标末尾隐式附加空字符(因此,在这种情况下,目标可能不是以空结尾的 C 字符串)。
strncpy 不会向字符串添加空终止符,因此在使用此函数时,字符串末尾会出现垃圾。
关于c - strncpy 行为与 sprintf 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13439627/