Access a 1D array as a 2D array in C++

后端 未结 4 1834
被撕碎了的回忆
被撕碎了的回忆 2021-01-03 23:26

This has bothered me for a while. A lot of times I find myself making a large buffer to hold a \"maximum\" amount of data. This helps me avoid dynamically allocating and dea

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-04 00:15

    If you know your row/column length (depending on row or column major and what not)... I believe it's something like...

    char get_value(char *arr, int row_len, int x, int y) {
        return arr[x * row_len + y];
    }
    

    ... for treating a 1D array as 2D.

    Another thing for 2D dynamic C arrays.

    char **arr = (char **)malloc(row_size * sizeof(char *));
    int x;
    for (x = 0; x < row_size; ++x) {
        arr[x] = (char *)malloc(col_size * sizeof(char));
    }
    

    I could have my columns and rows mixed though...

    Like everyone else has said, vectors are nice since you're using C++:

    auto matrix_like_thing = std::vector >(rows, std::vector(cols, '\0'));
    matrix_like_thing[0][4] = 't';
    

提交回复
热议问题