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

C言語 scanfで数値をやり取りするときに&をつける理由

Last updated at Posted at 2020-02-27

参照する場所を扱うのがポインタ

ポインタは使って参照する場所(アドレス)を受け渡しするための型です。

scanf関数で&をつける理由

C言語で作られたプログラムとお話するために使っているのが、__terminal__という通訳。
※Windowsだとコマンドプロンプト

ここから数値を入力したり、プログラムとやり取りをしています。

scanfはterminalとやり取りをするためにあるプログラムです。
以下の書き方はterminalに対して、変数のポインタを渡しています。

「住所を渡すから、その中に値を入れて返してね!」

ということをやっています。

scanf("%d",&a);

もし、&を付けないで、変数自体を渡したらどうなるでしょうか。
これは、住所ではなく、箱の中身を渡していることと一緒です。(厳密にいえば箱の中身のコピー)

箱の中身(中身のコピー)を渡されてもterminalは中身を入れ替えることができません。

terminalに対して、変数を渡してもterminalは変更を加えることができません。

なのでscanfではポインタを渡せるように&を付けてやり取りをしています。

参考

&つけが必要な変数の正体 - 苦しんで覚えるC言語
https://9cguide.appspot.com/15-03.html

0
0
4

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?