gpt4 book ai didi

c - strncpy 的行为与 sprintf 的不同

转载 作者:行者123 更新时间:2023-12-04 05:23:43 25 4
gpt4 key购买 nike

我正在使用以下代码创建一个用于测试哈希表的“ 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/

如果 source 比 num 长,则不会在目标末尾隐式附加空字符(因此,在这种情况下,目标可能不是空终止的 C 字符串)。

strncpy 不会向您的字符串添加空终止符,因此在使用此函数时,您的字符串末尾会出现垃圾内容。

关于c - strncpy 的行为与 sprintf 的不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13439627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com