0

我正在尝试编写一个程序,它合并来自标准输入的行并仅打印那些超过 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:::
4

2 回答 2

2

您没有current_sentence以空字符 ( '\0') 终止。如果要printf正确打印字符串,最好确保它以空值结尾。

顺便说一句,不需要第二个malloc。重用分配给的内存current_sentence而不重新分配。

另请注意,您没有正确释放分配的内存。您应该free为每个malloc. 也许现在这不是问题,但它会造成内存泄漏

你的循环应该是这样的:

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

再说一次,正如评论中提到的那样fgets,您确实宁愿让自己为您完成工作。

于 2013-11-05T08:26:43.370 回答
0
char *text[BUFFERSIZE];

应该

char text[BUFFERSIZE];
于 2013-11-05T08:23:55.773 回答