【发布时间】:2021-07-06 05:12:30
【问题描述】:
函数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);
}
其中STARTING_SIZE_OF_BUFFER 是您在每次分配中增加缓冲区的大小。因此,首先缓冲区有STARTING_SIZE_OF_BUFFER 单元格要填充字符指针,然后如果需要,大小增加一倍,依此类推。 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]);
}
}
其中CHARACTERS_PER_LINE 是一个常数,用于指示每行应打印多少个字符。
注意: 两个函数中的形参都声明为 void 指针,因为需要处理 structPointer 是指向链表的指针的情况,但这与现在。
有时该函数会将输入存储为给定的,有时它会在缓冲区中存储一些非 ASCII / 不正确的字符。不同的编译器也会向我显示不同的结果,例如,2 个正在运行的捕获(程序应该将文本打印为一个块):
【问题讨论】: