C readText函数没有';t在动态缓冲区中正确存储标准输入
函数C readText函数没有';t在动态缓冲区中正确存储标准输入,c,stdin,C,Stdin,函数readText读取标准输入,并将其存储在动态缓冲区中(新行字符和输入中不需要的“\0”除外)readText获取指向缓冲区第一次分配的指针。在main中,缓冲区在main中分配: int main() { char* buffer = calloc(STARTING_SIZE_OF_BUFFER, sizeof(char*)); char** bufferPointer = malloc(sizeof(char**)); *bufferPointer = buffe
readText
读取标准输入,并将其存储在动态缓冲区中(新行字符和输入中不需要的“\0”除外)readText
获取指向缓冲区第一次分配的指针。在main中,缓冲区在main中分配:
int main() {
char* buffer = calloc(STARTING_SIZE_OF_BUFFER, sizeof(char*));
char** bufferPointer = malloc(sizeof(char**));
*bufferPointer = buffer;
readText(isBuffer, bufferPointer); /*read text and store memory state */
printText(isBuffer, bufferPointer);
}
其中,start\u SIZE\u OF\u BUFFER
是您在每次分配中增加缓冲区的大小。因此,首先缓冲区有开始的\u buffer的\u SIZE\u
单元格要填充字符指针,然后如果需要,两倍大小,依此类推。readText
的实现是:
int readText(void* structPointer)
{
char* buffer = *(char**)(structPointer); /* structPointer is a pointer to a memory block */
int noOfBlocks = 1; /* number of buffer allocations */
int i, c;
for (i = 0; (c = getchar()) != EOF; i++)
{
if (c == '\n')
{
i--; /* no need to advance in buffer index, in next iteration i will be the same as before
the decrement */
continue;
}
if (i == STARTING_SIZE_OF_BUFFER) /* need to allocate space */
{
buffer = realloc(buffer, STARTING_SIZE_OF_BUFFER * (noOfBlocks + 1)); /* times (noOfBlocks + 1) to increase the
current buffer size by STARTING_SIZE_OF_BUFFER */
if (buffer == NULL) /* couldn't a bigger memory block */
return -1;
noOfBlocks++;
buffer[i] = c;
}
else
buffer[i] = c;
}
buffer[i] = '\0'; /* indicate end of text */
*(char**)(structPointer) = buffer;
return 1;
}
还有一个函数printText
,用于打印给定缓冲区中的文本。实施情况如下:
void printText(void* structPointer)
{
char* buffer = *(char**)structPointer; /* structPointer is a pointer to a memory block */
int i; /* buffer index */
for (i = 0; buffer[i] != '\0'; i++)
{
if (i % CHARACTERS_PER_LINE == 0 && i != 0) /* if the program wrote */
printf("%c", '\n');
printf("%c", buffer[i]);
}
}
其中,每行字符数
是一个常数,用于指示每行应打印多少字符
注意:这两个函数中的形式参数都声明为void指针,因为需要处理structPointer
是指向链接列表的指针的情况,但这与现在无关
有时该函数将按给定方式存储输入,有时它将在缓冲区中存储一些非ASCII/不正确的字符。不同的编译器也会显示不同的结果,例如,2个正在运行的捕获(程序应将文本打印为块):
我建议您使用返回值调试这些函数,而不是只返回1尝试设置标准错误返回值,以及每种情况下的错误返回值,例如,如果
c
变量是非ASCII字符return-1
。
另外,realloc()
和calloc()
总是返回一个void
类型指针,因此您必须对其进行强制转换,这很可能是因为您的程序行为错误
char** bufferPointer = malloc(sizeof(char**));
不一定。malloc返回一个指向分配内存中第一个字符指针的指针