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?

scanf関数の'&'

Posted at

scanf関数は、第2引数で受け取ったアドレスに、読み込んだ値を書き込む。
うっかり変数を渡すと、そこに格納されている値をアドレスとして認識してしまう。

scanf関数の'&'
#include <stdio.h>

int main()
{
    // 変数にscanfで読み込んだ値を格納
    // nはint型の整数なので、scanfに渡すときには&が必要
    int n;
    scanf("%d", &n);
    printf("読み込んだ値は%d\n", n);

    // 配列にscanfで読み込んだ値を格納
    // array[i]は配列要素であり、int型の整数なので、scanfに渡すときには&が必要
    int array[5];
    for (int i=0; i<5; i++){
        printf("array[%d] : ", i);
        scanf("%d", &array[i]);
    }
    for(int i=0; i<5; i++)
        printf("array[%d] = %d\n", i, array[i]);

    // 配列に文字列を格納
    // ここで渡したいのは配列変数の先頭アドレス。
    // 「添え字なしの配列名」は先頭のアドレスを直接表すので、ここでは&は不要
    char str[10];
    printf("文字列を入力 : ");
    scanf("%9s", str);
    printf("入力されたのは%s\n", str);
    
    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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?