在 fill_text() 函数中,我使用 realloc 扩展文本(指向结构数组的指针)。但是 realloc() 在这里抛出一个错误(在 fill_sent 函数中,该函数工作正常)。可能是什么问题呢?(强制类型转换没有帮助)
,
#include <stdio.h>
#include <stdlib.h>
struct Sentence{
char* string;
int len;
};
int fill_sent(struct Sentence* sent){
int i = 0, nl_counter = 0;
char c;
sent->string = (char*)malloc(3 * sizeof(char));
while( (c = getchar()) != '.' && c != '?' && c != '!'){
sent->string[i] = c;
if(c == '\n'){
nl_counter++;
if (nl_counter == 2)
return 0;
}
++i;
sent->string = realloc(sent->string, (i + 3) * sizeof(char));
}
sent->string[i] = '.';
sent->string[i + 1] = '\0';
sent->len = i + 1;
return 1;
}
int fill_text(struct Sentence *text){
int i = 0;
while(fill_sent(&text[i])){
i++;
text = realloc(text, sizeof(struct Sentence) * (i + 1));
}
return i;
}
void print_text(struct Sentence *text, int len){
for(int i = 0; i < len; ++i){
printf("\n%s\n", text[i].string);
}
}
int main(){
struct Sentence* text = malloc(sizeof(struct Sentence));
int len = fill_text(text);
print_text(text, len);
}