대략 2차원 배열을 만들 때, 아래와 같이 했는데,

이렇게 하면 연속된 메모리 상에 배열이 잡히지 않는다.
요렇게 하려면 될라나 ...


이렇게 해도 잘 돌아가긴 한데,
혹시 더 아름다운 방법이 있다면 알려주시길 ...

Trackback Address :: http://seirion.com/trackback/185 관련글 쓰기

댓글을 달아 주세요

  1. |꼬마늑대| 2010/06/25 15:41 Address Modify/Delete Reply

    C도 아니고 C++이니까 클래스로 만드는 건 어때?

    class CMultiArray
    {
    protected:
    int size[3];
    int* m_pMem;
    public:
    // 1차원 배열
    CMultiArray(size_t s)
    {
    m_pMem = new int[s];
    size[0] = s;
    size[1] = 1;
    size[2] = 1;
    }
    // 2차원 배열
    CMultiArray(size_t s1, size_t s2)
    {
    m_pMem = new int[s1 * s2];
    size[0] = s1;
    size[1] = s2;
    size[2] = 1;
    }
    // 3차원 배열
    CMultiArray(size_t s1, size_t s2, size_t s3)
    {
    m_pMem = new int[s1 * s2 * s3];
    size[0] = s1;
    size[1] = s2;
    size[2] = s3;
    }

    // 1차원 접근
    int& operator[](size_t s)
    { return m_pMem[s]; }
    // 1차원 접근
    int& operator()(size_t s)
    { return m_pMem[s]; }
    // 2차원 접근
    int& operator()(size_t s1, size_t s2)
    { return m_pMem[s1 * size[0] + s2]; }
    // 3차원 접근
    int& operator()(size_t s1, size_t s2, size_t s3)
    { return m_pMem[s1 * size[1] + s2 * size[0] + s3]; }
    };

    // 2차원 생성해서
    CMultiArray arr(64, 32);

    // 1차원으로도 쓰고
    for (int i = 0; i < 64 * 32; i++)
    arr[i] = i;

    // 2차원으로도 쓰고
    for (int y = 0; y < 2; y++)
    {
    for (int x = 0; x < 64; x++)
    printf("arr(%d,%d) = %d\t", y,x, arr(y,x));
    printf("\n");
    }




    하지만 난 그냥 이렇게 쓴다는거..
    int* mem = new int[64*32];
    for (int y = 0; y < 32; y++)
    for (int x = 0; x < 64; x++)
    printf("%d,%d = %d\n", y,x, mem[y * 64 + x]);

    • 바보세룐 2010/06/25 19:41 Address Modify/Delete

      껄껄 ! 장문의 리플 감사합니다.
      하지만 결국 사람들은 [] 오퍼레이터에 익숙해 져 있다는 점과,
      2차원 배열은 개념적으로 [][] 이렇게 이차원 적으로 표시하는 게 쉽다는 점에서 제가 쓴 두 가지 중에 하나를 쓰는 게 낫지 않을까라고 생각했던 겁니다.
      개인적으론 후자가 맘에 드는군효 ㅎㅎ

    • |꼬마늑대| 2010/06/28 10:04 Address Modify/Delete

      루프의 규모가 크다면 아래와 같이 쓰는 것도 좋습니다.

      uchar* realMem = new int[640*480*3];

      uchar* loopPtr; // 루프에 쓸 임시 포인터
      for (int y = 0; y < 480; y++)
      {
      // 포인터의 위치를 y축 기준으로 재설정
      loopPtr = realMem + y * 640 * 3;

      for (int x = 0; x < 640; x++)
      {
      // 포인터를 맘껏 쓰고
      loopPtr[0] = 255;
      loopPtr[1] = 0;
      loopPtr[2] = 255;
      // x축 방향으로 한 픽셀씩 이동
      loopPtr += 3;
      }
      }