首页 > 解决方案 > 重新分配结构

问题描述

我有一个可以修改的 2d char 数组的结构,我应该能够增加 2d 数组中的行数,我设法做到了,但我遇到了一个问题,在第四行之后我无法分配更多空间,我尝试将数组的长度更改为更小,在这种情况下,同样的问题在四次后一致,并且 realloc() 的返回值不是 NULL,我无法退出程序。

这是结构:

struct Buffer{
    /*--buffer--*/
    
    /*2d array that store the whole text */
    char **text;
    /* number of rows */
    int count;
};

程序读取文本并在 60 个字符后创建一个新行

    /*initialize a buffer */
    struct Buffer* buffer = (struct Buffer*)malloc(sizeof(struct Buffer));
    buffer->text = (char**)malloc(sizeof(char*));
    buffer->text[0] = (char*)malloc(sizeof(char)*61);
    buffer->count = 1;
    /*start reading the text*/
    readText(1, buffer);
    printf("\nFixed output: \n");
    /*print the text*/
    printText(1, buffer);

在 readText() 里面

    /* try to add more memory for the ADT */
    buffer->text[buffer->count-1][60] = '\0';
    if(!expandADT(1, buffer)) exit_error(0);
    buffer->text[buffer->count-1][0] = c;

int expandADT(int option, void *ptr)

    /* cast the pointer */
    struct Buffer* buffer = (struct Buffer*) ptr;
    struct Buffer* temp;
    /* increase the number of rows */
    buffer->count++;
    /* try to make space for another row */
    temp = (struct Buffer*)realloc(buffer, sizeof(*buffer->text) * buffer->count);
    /* if the buffer is NULL it means that we don't have enough space and we return an error*/
    if(temp == NULL) return 0;
    buffer = temp;
    buffer->text[buffer->count-1] = (char*)malloc(sizeof(char)*61);
    if(buffer->text[buffer->count-1] == 0) return 0;

如果数组空间不足,它应该打印一条消息并关闭程序,但是术语

if(temp == NULL) return 0;

expandADT()中不正确,程序继续运行。然后它停在代码行 -

buffer->text[buffer->count-1][0] = c; /* c is an input character */

在程序尝试扩展数组之后的readText()处。

对于大于 60*4 的输入。该程序没有任何输出,它会关闭。

标签: cstructrealloc

解决方案


推荐阅读