【问题标题】:readText function doesn't properly store standard input in a dynamic bufferreadText 函数未将标准输入正确存储在动态缓冲区中
【发布时间】: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 个正在运行的捕获(程序应该将文本打印为一个块):

【问题讨论】:

    标签: c stdin


    【解决方案1】:
    char** bufferPointer = malloc(sizeof(char**));
    

    不一定。 malloc 返回一个指向分配内存中第一个 char 指针的指针。

    【讨论】:

      【解决方案2】:

      我建议您使用返回值来调试这些函数,而不是只返回 1 尝试设置标准错误返回值,并为每种情况设置一个错误返回值,例如,如果 c 变量是非 ASCII字符return -1。 还有realloc()calloc() 总是返回一个void 类型指针,所以你必须强制转换它,很可能是你的程序因此而表现错误

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-09-28
        • 2013-07-31
        • 2019-12-12
        • 1970-01-01
        • 2023-04-08
        • 2016-12-13
        • 1970-01-01
        相关资源
        最近更新 更多