#include "head.h"
void readText(char *buffer)
{
char c;
int count=0;
char *newBuffer =(char *)calloc(SIZE,sizeof(char));
if(newBuffer==NULL)exit(1);
int i=1;
while ((c = getchar()) != EOF)
{
if (count % SIZE == 0)
{
i++;
newBuffer = (char *)realloc((char *)buffer,i*SIZE);
if(newBuffer==NULL){
printf("Not enought space, bye");
exit(1);
}else{
buffer=newBuffer;
}
}
if (c != '\n'){
*buffer++ = c;
count++;
}
}
}
int main()
{
int choose;
char *buffer;
printf("Please choose the desired method:\n Press 0 for buffer-method.\nPress 1 for Linked List method\n");
scanf("%d", &choose);
buffer = (char *)calloc(SIZE, sizeof(char));
if (buffer == NULL){
printf("Something went wrong, please try again\n");
exit(1);
}
readText(buffer);
printf("%s", buffer);
free(buffer);
return 0;
}
}
所以我的任务是编写一个函数,读取文本,每次超过 60 个字符时,我都需要重新分配。现在一切正常,直到我使用 call,这意味着如果我从用户那里得到超过 60 个字符,我会收到一个错误,并且终端指向 realloc 的问题。 有什么问题?