为什么我使用 strncpy 复制的字符串有垃圾而不是最后一个字符?

Why does the string I copied using strncpy have junk instead of the last character?

我分配了一个名为 "locations" 的结构数组。在所述结构中有一个名为 "country" 的元素。我创建了一个字符串,您可以在下面看到其中包含 "United States"。我 malloc'd space 来保存字符串(我必须这样做)并尝试使用 strncpy 将字符串放入 malloced space.

这在我的代码的其他地方适用于从文件中读入的字符串,但不适用于我直接声明的这个字符串。

当我打印出结果时,它说结构持有 "United State(error symbol)"

所以 "United States" 末尾的 s 是错误符号。

错误符号看起来像一个由 1 和 0 组成的小方框。

char *US_string = "United States";
locations[0].country = malloc(sizeof(US_string));
strncpy(locations[0].country, US_string, strlen(US_string));

有人知道发生了什么事吗?

感谢您的帮助!请不要对我太苛刻,我是 CS 专业的一年级学生。只是想把这个错误从实验室中移除。

mallocing 需要通过添加 1 来调整以解决 '[=12=]'。此外 sizeof(US_string) 将给出指针的大小,这可能与实际字符串大小不同。因此

locations[0].country = malloc(strlen(US_string) + 1);

并且缺少 locations[0].country[strlen(US_string)] = '[=13=]'

sizeof 将 return 指针大小,而不是字符串大小。使用 strlen +1(以说明 0 字符串终止字符):

locations[0].country = malloc(strlen(US_string)+1);