0
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 1 year has passed since last update.

【C言語】1分でわかる!ポインタ【初学者向け】

Last updated at Posted at 2023-10-30

C言語初学者の最初のつまづきポイント、ポインタ。
意外と難しくないので、簡単かつ簡潔に解説しようと思う。

ポインタは単なるアドレス格納箱

例えば、

int a;

a = 10;

これは、aというint型(=4byte分)メモリを確保し、そこに整数10を代入していることになる。
これと同様に、

int *ptr;

ptr = &a;

これは、prtというint*型、すなわちint型メモリのアドレスを入れるためのメモリ(ポインタは型によらず4byte分)を確保し、そこにa(=int型メモリ)のアドレスを代入している。

(追記[11/13]ポインタに割り当てられるメモリの大きさについて、ポインタ変数のサイズ を参考にし、4byteと記してしまったが、正しくはOS依存でした。日々、コレ勉強コメントにてご指摘ありがとうございます。)

また、ポインタに*をつけることで、そのメモリに入っているアドレスにあるデータを指すことができる。
すなわち、以下の二つは同じ結果を出力する。

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

(追記[11/13]*についての説明を追加いたしました。ご指摘ありがとうございます。)

まあ、ここまでで理解できたという方は天才であろう。
図を用いて具体的に見ていく。

ポインタを図解

以下のようなコードがあったとする。

// ④
void hoge(int* c){
	printf("%p\n", c);
	printf("%d\n", *c);
}

int main(){
	// ①
	int a;
	int *b;
	
	// ②
	a = 10;
	b = &a;

	// ③
	hoge(b); // アドレスを渡している!

	//⑤
	printf("%p\n", &b); // 0xa1
	printf("%p\n", b); // 0x01
	printf("%d\n", *b); // 10
}

以下の図と対応している。
image.png
image.png

ちょっとだるいけど頑張って見てください。きっと理解できるはず。

何か質問・ご指摘等あればコメントください。

追記:ご指摘ありがとうございます。単純な間違いについては訂正いたしました。

0
1
7

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