0
0

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 3 years have passed since last update.

複数の多次元配列を指すポインタの配列

Posted at

先日、複数の多次元配列を指すポインタの配列を実装しようとして手こずったので備忘録がてら記事を書く。

達成したかったこと

複数定義された多次元配列に変数操作でアクセスしたい。
例えば下図に示すように、PtrArray[0]とすれば配列aにアクセスでき、PtrArray[1]とすれば配列bにアクセスできるといった具合。

image.png

実装

#include <stdio.h>

const unsigned char a[2][3] = {{0, 1, 2}, {3, 4, 5}};
const unsigned char b[2][3] = {{10, 11, 12}, {13, 14, 15}};
const unsigned char c[2][3] = {{100, 110, 120}, {130, 140, 150}};

// unsigned char型のデータを指し示すポインタの配列(配列のアドレスを格納)
const unsigned char *PtrArray[3] = {
    a,
    b,
    c,
};

int main(void)
{
    unsigned char (*p)[3];
    p = PtrArray[1];       // 右辺の要素番号で指し示す配列を切り替える。この場合は配列bを指し示すようにする。

    // 配列bから値14を取得する
    printf("val: %d\n", *(p[1]+1));

    // もちろん、単純にこれでもOK(突然の+4は困惑するかもしれない。)
    printf("val: %d\n", *(PtrArray[1]+4));
}
0
0
3

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?