如何使用fgets()重新分配多个数组

时间:2019-06-21 00:42:58

标签: c arrays fgets realloc

我正在尝试使用fgets()读取某些输入,但是我需要将输入存储在名为userNumbers的动态数组中,我应该如何获取realloc()才能与fgets()一起使用?当我尝试读取8个以上的元素时,我的程序中断了(即1,2,3,4,5,6,7,8有效,但是1,2,3,4,5,6,7,8,9,10才不是)。另一件事是我必须使用fgets()。预先感谢。

size_t capacity = 4;
size_t size = 0;
char* userNumbers = (char*)malloc(capacity * sizeof(char));
char** realNumStr = (char**)malloc(capacity * sizeof(char*));
double* realNumDouble = (double*)malloc(capacity * sizeof(double));
double* realNumDoubleFinal = (double*)malloc(capacity * sizeof(double));
double* realNumDoubleMedian = (double*)malloc(capacity * sizeof(double));

if (userNumbers == NULL || realNumDouble == NULL || realNumDoubleFinal == NULL || realNumStr == NULL)
{
    printf("insufficient Memory");
    return EXIT_FAILURE;
}

//User's input
while (fgets(userNumbers, capacity, stream))
{
    size += strlen(userNumbers);

    while (size >= capacity)
    {
        capacity = size * 2;

        char* userNumbers2 = realloc(userNumbers, capacity * sizeof(char)+1);
        char** realNumStr2 = realloc(realNumStr, capacity * sizeof(char*)+1);
        double* realNumDouble2 = realloc(realNumDouble, capacity * sizeof(double));
        double* realNumDoubleFinal2 = realloc(realNumDoubleFinal, capacity * sizeof(double));

        if (userNumbers2 == NULL || realNumDouble2 == NULL || realNumDoubleFinal2 == NULL || realNumStr2 == NULL)
        {
            free(userNumbers);
            free(realNumDouble);
            free(realNumDoubleFinal);
            free(realNumStr);

            printf("insufficient Memory");
            return EXIT_FAILURE;
        }
        userNumbers = userNumbers2;
        realNumStr = realNumStr2;
        realNumDouble = realNumDouble2;
        realNumDoubleFinal = realNumDoubleFinal2;
    }

// ...代码继续... }

//抛出错误: HEAP [rstats.exe]:指定给RtlValidateHeap(0000026E15F20000,0000026E15F298F0)的无效地址 stat.exe触发了一个断点。

断点在这里触发: 如果(!has_cctor)             _cexit();

1 个答案:

答案 0 :(得分:0)

您应该首先阅读所有输入。每次使用fgets()读取一行时,都需要将其连接到包含所有行的缓冲区中。那是您应该重新分配的缓冲区,可以对fgets()调用使用固定大小的缓冲区。

char line[100];
char *numbersStr = NULL;
size_t size = 0;

while (fget(line, sizeof(line), stream) {
    size_t linelen = strlen(line);
    char *newNumbersStr = realloc(numbersStr, size + linelen + 1);
    if (!newNumbersStr) {
        free (numbersStr);
        printf("insufficient Memory");
        return EXIT_FAILURE;
    }
    numbersStr = newNumbersStr;
    strcpy(&numbersStr[size], line);
    size += linelen;
}

当您进入stream的EOF时,此循环将结束。然后,您可以将numbersStr中的所有数字解析为numbersArray,然后在该循​​环中将其与realloc()一起增长。