2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Cで負のIndexが使える2次元配列を動的にかつ連続に確保する

Posted at

物理シミュレーションをやってますが、配列で負のIndexが使いたくなってやってみました。
以外とさくっとできた。

下記のような使い方をイメージして書いてます

2次元配列、myArray[j][i]のi, jは

imin <= i < imax
jmin <= j < imax

imin < 0
jmin < 0

imax >= 0
jmax >= 0

メモリアクセスが連続となる方をiとしています。i, jの順番に注意してください。

    #include <iostream>

    int **allocateNegativeIndex2DimArray(
        int jmin,       /* array[jmin][] jmin  < 0 */
        int jmax,       /* array[jmax][] jmax >= 0 */
        int imin,       /* array[][imin] imin  < 0 */
        int imax        /* array[][imax] imax >= 0 */
    )
    {

        const int ni = imax - imin;
        const int nj = jmax - jmin;
        const int numTotal = ni * nj;
        
        int **tmp = (int **)malloc(nj * sizeof(int));
        tmp[0] = (int *)malloc(numTotal * sizeof(int));
        
        for (int j = 1; j < nj; j++) {
            tmp[j] = tmp[j - 1] + ni;
        }
        
        const int icenter = abs(imin);
        const int jcenter = abs(jmin);

        int **val = &tmp[jcenter];
        for (int j = jmin; j < jmax; j++) {
            val[j] = &tmp[j + jcenter][icenter] + ni;
        }

        return val;
    }

    int main() {
        
        int xmin = -2;
        int xmax =  3;
        int ymin = -1;
        int ymax =  2;
        
        int **myArray = allocateNegativeIndex2DimArray(ymin, ymax, xmin, xmax);

        /*
         * 実際に負のインデックスが入るか表示テストする
         */
        for (int j = ymin; j < ymax; j++){
            for (int i = xmin; i < xmax; i++) {
                myArray[j][i] = i * j;
                printf("myArray[%2d][%2d] = %3d\n", j, i, myArray[j][i]);
            }
        }
        return 0;
    }
myArray[-1][-2] =   2
myArray[-1][-1] =   1
myArray[-1][ 0] =   0
myArray[-1][ 1] =  -1
myArray[-1][ 2] =  -2
myArray[ 0][-2] =   0
myArray[ 0][-1] =   0
myArray[ 0][ 0] =   0
myArray[ 0][ 1] =   0
myArray[ 0][ 2] =   0
myArray[ 1][-2] =  -2
myArray[ 1][-1] =  -1
myArray[ 1][ 0] =   0
myArray[ 1][ 1] =   1
myArray[ 1][ 2] =   2

2
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?