LoginSignup
13
9

More than 5 years have passed since last update.

配列とポインタ

Last updated at Posted at 2014-04-27

配列とポインタ

配列とポインタはほぼイコールです。

int x[] = { 1, 2, 3};
int *ptr = x;

このとき、 ptrx[0] のアドレスを指しています。アドレスの中身を見てみると x[0] の値が表示されます。

printf("%d\n", *ptr);

// => 1

x[1]ptr の次のアドレスになります。

printf("%d\n", *(ptr + 1));

// => 2

そのため、この様な処理は

for (ix = 0; ix < sizeof x / sizeof x[0]; ix++) {
    printf("%d\n", x[ix]);
}

このように書き換えることができます。
配列表現はポインタのシンタックスシュガーと言えます。

for (ix = 0; ix < sizeof x / sizeof x[0]; ix++) {
    /* printf("%d\n", x[ix]); */
    printf("%d\n", *(x + ix));
}

昔の処理系は配列表現をポインタで置き換えていたものがあるらしく、

for (ix = 0; ix < sizeof x / sizeof x[0]; ix++) {
    /* ixは配列でない! */
    printf("%d\n", ix[x]);
    /* -> printf("%d\n", *(ix+x)); */
}

こう書いてもコンパイルが通るものがありました。昔はあったよなーと思っていたら、今もありました。手元のgcc 4.7.2で-Wallをつけても何も言われずにコンパイルが通りました。

#include <stdio.h>

int main(int argc, char** argv) {

    int x[] = {1, 2, 3};
    int ix;
    int *ptr = x;

    printf("%d\n", *ptr);
    printf("%d\n", *(ptr+1));

    for (ix = 0; ix < sizeof x/sizeof x[0]; ix++) {
        printf("%d\n", ix[x]);
    }

    return 0;
}
13
9
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
13
9