void replace(char* str) {
unsigned int len = 0;
unsigned int no_of_spaces = 0;
char* temp = str;
int* space_positions = NULL;
while (*temp) {
if ((char)*temp == SPACE) {
no_of_spaces++;
}
temp++;
len++;
}
printf("%d\n", len); / prints correct value
void* str_copy_allocation = (char*) malloc((sizeof(char) * len) + 1);
char* str_copy = NULL;
if (str_copy_allocation)
str_copy = str_copy_allocation;
else {
fprintf(stderr, "Invalid allocation occured");
perror("Error printed by perror");
}
temp = str; // point to starting of str
while (*temp != '\0') {
*str_copy++ = *temp++;
printf("%c\n", *str_copy);
}
str_copy[len] = '\0';
printf("%s\n", str_copy);
temp = str_copy; // to the start of str_copy
unsigned int new_len = len + 2 * no_of_spaces + 1;
str_copy = realloc(temp, new_len);
if (str_copy == NULL) {
fprintf(stderr, "Invalid reallocation occured");
perror("Error printed by perror");
}
str_copy[new_len] = '\0';
printf("%s\n", str_copy);
}
在这里,我试图复制一个char数组,然后增加其大小。Aborted (core dumped)
当我将的值复制到时,我得到temp
了str_copy
。由于str
是用户定义的字符串,为了增加其大小,我必须对其进行复制。该副本为str_cpy
,然后我将增加的大小str_cpy
并将其作为新字符串返回。
printf("%c\n", *str_copy);
while循环中的print语句将打印空字符!
可能是什么原因?
您有两个问题,首先是由于user312023指出str_copy[len] = '\0';
str_copy行已增加。您需要str_copy = str_copy_allocation;
在这一行的上方指向字符串的开头。
另一个问题是您的printf循环
while (*temp != '\0') {
*str_copy++ = *temp++;
printf("%c\n", *str_copy);
}
打印时str_copy已经增加,因此您要打印str_copy中的下一个字符(尚未从temp复制该字符)。要查看复制的内容,应在打印后增加str_copy,如下所示
while (*temp != '\0') {
*str_copy = *temp++;
printf("%c\n", *str_copy++);
}
通过这两个更改,代码可以正常工作。
编辑:另一个问题是,当您通过重新分配扩大字符串,并将null终止符放在最后时,您的字符串在position处已经有一个null终止符,该终止符str_copy[len]
是从较小长度的字符串复制而来的。因此,作用于该字符串的任何函数都不会考虑您分配的额外内存,因为它们将在第一个空终止符处停止。
为了说明这一点,请尝试在某些字符串上使用该函数,例如 replace("my string");
然后在函数中,在最后一个printf之前的末尾,添加类似的内容str_copy[len+1]='x';
。
您会注意到此x不是打印出来的,因为在重新分配更多内存之前,printf停在了第一个空终止符(即字符串的“末尾”)处。如果改用str_copy[len]='x'; str_copy[len+1]='x'
,则将同时打印两个x,因为您已覆盖了从珍贵字符串复制的空终止符。
因此,要解决此问题,只需str_copy[len]=' ';
在表示的行之前或之后放置str_copy[new_len]='\0';
,这将覆盖较小字符串中的空终止符。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句