【发布时间】:2020-03-06 13:24:18
【问题描述】:
我想知道是否有一种方法可以将字符串数组初始化为我在内存分配期间决定的值,这样它就不会包含任何垃圾并且空字符将被放置在正确的位置。我知道使用 calloc 分配的内存被初始化为全零,但在这种涉及字符串的情况下它没有帮助。
我练习在 C 中使用指针和分配内存。 有一个练习,我编写了一个用于将一个字符串复制到另一个字符串的函数 - 在 main() 中,我根据用户提供的字符串长度使用 malloc 为两个字符串分配内存,然后用户输入第一个字符串。 此时我将第一个字符串和第二个字符串(未初始化)的指针作为参数发送给 strCopy(char* str1, char* str2)。在该函数中,我还使用了我编写的另一个基本函数来计算字符串的长度。但是你可能猜到了,由于第二个字符串充满了垃圾,所以函数内部的长度计算是混乱的。
void strCopy(char* str1, char* str2)
{
int str1len = str_len(str1); // basic length calculating function
int str2len = str_len(str2);
int i;
for (i = 0; i < str2len; i++)
{
str2[i] = str1[i];
}
str2[i] = '\0';
if (str2len < str1len)
printf("There wasn't enought space to copy the entire string. %s was
copied.\n", str2);
else
printf("The string %s has been copied.\n", str2);
}
现在在 main() 的循环中初始化 str2 时它工作正常,但我对其他可能的解决方案感兴趣。
非常感谢您的帮助!
【问题讨论】:
-
此代码存在严重缺陷。您不能使用字符串长度来衡量可用空间。
-
在两个日志消息中,您传递相同的字符串。这有帮助吗?
标签: c malloc dynamic-memory-allocation calloc