C中的动态2D数组不读取第一个元素

时间:2018-11-22 16:54:02

标签: c

我的大学让我编写了一个程序,该程序读取输入并将其存储到动态2D数组中,但是我们没有涉及该主题。我的实现遇到问题,因为它跳过了每一行的第一个字符。我知道代码不是最高质量,但是我不知道为什么它会跳过第一个字符。

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>


#define MULT 3
#define DIV 2

char *read_line(int *col_size, int *max_c) {
    char *line = NULL;
    int size = *col_size;
    int i, c;
    line = malloc(size * sizeof *line);
    for (i = 0; ((c = getchar()) != '\n') && (c != EOF); ++i) {
        if (i == size) {
            size = 1 + size * MULT / DIV;
            line = realloc(line, size * sizeof *line);
            assert(line != NULL);
        }
        line[i] = c;
    }
    if (i > *max_c)
        *max_c = i;
    if (size > *col_size)
        *col_size = size;
    return line;
}

char **read(int *row, int *col) {
    char **input = NULL;
    int row_size = 0;
    int col_size = 0;
    int i, c;
    int max_c = 0;

    for (i = 0; (c = getchar()) != EOF; ++i) {
        if (i == row_size) {
            row_size = 1 + row_size * MULT / DIV;
            input = realloc(input, row_size * sizeof *input);
            assert(input != NULL);
        }
        input[i] = read_line(&col_size, &max_c);
    }
    *row = i;
    *col = max_c;
    return input;
}


int main(void) {
    int row_size, col_size, i, j;
    char **board = read(&row_size, &col_size);
    for (i = 0; i < row_size; ++i) {
        for (j = 0; j < col_size; ++j)
            putchar(board[i][j]);
        putchar('\n');
    }
    free(board);
    return 0;
}

1 个答案:

答案 0 :(得分:1)

for (i = 0; (c = getchar()) != EOF; ++i) {
read()中的

read_line()看到之前先吃掉了第一个字符。您将必须找到其他方法来检查EOF。例如,

for (i = 0; !feof(stdin); ++i) {

此外,您不会对字符串进行零终止。将阅读循环更改为

char *read_line(int *col_size, int *max_c) {
    int size = *col_size ? *col_size : 1;  // at least 1 for the terminating 0
    char *line = malloc(size * sizeof *line);

    if(!line)
        return NULL;

    int i, c;
    for (i = 0; ((c = getchar()) != '\n') && (c != EOF); ++i) {
        if(i == size) {
            size = 2 + size * MULT / DIV;  // note the 2
            // ...
        }
        // ...
    }
    line[i] = '\0';

这样做。


for (i = 0; i < row_size; ++i) {
  for (j = 0; j < col_size; ++j)
      putchar(board[i][j]);  // accesses memory that isn't yours
  putchar('\n');             // if not all rows are of the same length.
}

为避免越界读取内存,请将其更改为

for (i = 0; i < row_size; ++i) {
    for (j = 0; board[i][j] != '\0'; ++j)
        putchar(board[i][j]);
    putchar('\n');
}

因为您现在有了以零结尾的字符串。还是为什么不只使用puts()

for (i = 0; i < row_size; ++i)
    puts(board[i]);

free(board);

那不会释放分配给行的内存。您必须

for (i = 0; i < row_size; ++i)
    free(bard[i]);
free(board);