LoginSignup
0
0

More than 5 years have passed since last update.

Pointerの超基礎学習#2

Posted at

ポインタについての学習メモ。ポインタのポインタになると少しこんがらがる。

#include <stdio.h>

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

    /*
      文字列の配列
    */
    //char型のポインタの配列
    char *strings[] = {"Hello", "Pointer", "World"};

    printf("%s %s %s\n", strings[0], strings[1], strings[2]); // -> Hello Pointer World

    /*
      ポインタのポインタ(多重間接参照)
    */
    int num = 100;

    //ポインタ変数宣言と初期化
    int *p = &num;

    //ポインタのポインタ変数宣言と初期化
    int **pp = &p;

    **pp = 150;

    printf("%d, %d, %d\n", num, *p, **pp); // -> 150, 150, 150


    /*
      ポインタのポインタを使って配列の要素を間接参照する
    */
    //ポインタのポインタ変数を宣言
    char **str1;

    printf("%s %s %s\n", strings[0], strings[1], strings[2]); // -> Hello Pointer World

    //アドレスを代入(配列の0番目のポインタのアドレスを入れている)
    str1 = &strings[0];

    //配列の0番目のポインタを変更
    //なぜ **str1 = "difficult"ではないのかを考えると**str1は文字列リテラルの0番目の文字へのポインタなので
    //配列内の文字列へのポインタを差し替えるには、配列の要素であるポインタを参照しなければならないため。
    // **str1 -> 配列の0番目のアドレスを参照して得た文字列の0番目のアドレスを参照(strings[0][0])と一緒
    // *str1 -> 配列の0番目のアドレスを参照(strings[0])と一緒
    *str1 = "difficult";

    //配列の要素が変更されている
    printf("%s %s %s\n", strings[0], strings[1], strings[2]); // -> difficult Pointer World

    //こちらからの変更も
    strings[0] = "Hello";

    //ポインタから得られる参照先も変更されている
    printf("%s\n", *str1); // -> Hello

    return 0;
}
0
0
0

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