我正在尝试编写一个程序,该程序合并来自stdin的行,并且只打印那些长度超过80个字符的句子。第一个找到的线路效果很好 - 但后面的线路是空的。我认为我在做错了
current_sentence = malloc(sentence_len);
。
如何正确重新分配字符串?
代码
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# define BUFFERSIZE 100
char* merge_string(char *text[], int n){
int i;
char *result = malloc(BUFFERSIZE * n);
for (i=0; i < n; i++){
strcat(result, text[i]);
}
return result;
}
int main(int argc, char *argv[]){
char buffer[BUFFERSIZE];
int i = 0;
char *text[BUFFERSIZE];
while(fgets(buffer, BUFFERSIZE, stdin) != NULL){
text[i] = strdup(buffer);
i++;
}
char *sentence = merge_string(text, i);
int sentence_len = strlen(sentence);
int j = 0;
int counter = 0;
char *current_sentence = malloc(sentence_len);
while (j < sentence_len){
current_sentence[counter] = sentence[j];
if (sentence[j] == '\n' && counter >= 80){
printf(":::HIT:::%s\n\n\n", current_sentence);
counter = 0;
current_sentence = malloc(sentence_len);
}
else if (sentence[j] == '\n'){
puts("Resetting counter");
counter = 0;
}
j++; counter++;
}
return 0;
}
输出
make 1_17; ./1_17 < example.txt
make: `1_17' is up to date.
Resetting counter
Resetting counter
:::HIT:::SHenri Cartier-Bresson (1908-2004) said "Your first 10,000 photographs are your worst," but he shot more than one an hour.)
Resetting counter
:::HIT:::
Resetting counter
:::HIT:::
答案 0 :(得分:2)
您没有使用空字符current_sentence
)终止'\0'
。如果您希望printf
正确打印字符串,最好确保它以空值终止。
顺便说一下,不需要第二个malloc
。重新使用为current_sentence
分配的内存,而无需重新分配。
另请注意,您没有正确释放分配的内存。您应该为每个free
使用匹配的malloc
来电。也许现在这不是问题,但它会创建一个memory leak。
你的循环应该是这样的:
while (j < sentence_len)
{
current_sentence[counter] = sentence[j];
if (sentence[j] == '\n')
{
if (counter >= 80)
{
current_sentence[counter + 1] = '\0'; // Make string null-terminated
printf(":::HIT:::%s\n\n\n", current_sentence);
}
else
{
puts("Resetting counter");
}
counter = 0;
}
else
{
counter++;
}
j++;
}
free(current_sentence); // Free allocated memory
然后,as mentioned in a comment,你宁愿让fgets
为你做的工作。
答案 1 :(得分:0)
char *text[BUFFERSIZE];
应该是
char text[BUFFERSIZE];