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

后端 未结 4 1835
被撕碎了的回忆
被撕碎了的回忆 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:08

    Once you only know the length of your array at runtime, I guess it is better to solve this problem not using an 2D array, but emulating it by using functions. For example, in C:

    char data1D[1000] = {0};
    
    unsigned int getElement(unsigned int x, unsigned int y, 
                unsigned int xMax, unsigned int yMax)
    {
      // Do some error tests
      return ((unsigned int *) data1D)[x*xMax + y];
    }
    

提交回复
热议问题