LoginSignup
5
4

More than 5 years have passed since last update.

C言語~ポインタ~

Posted at

アドレス演算子

オブジェクトに&演算子を適用すると,そのオブジェクトのアドレスが得られる
&a aのアドレス(aへのポインタを生成する)

ポインタ

Type x;
Type *p;

p = &x;

上の時,pはxを指すという.
Type型のオブジェクトxにアドレス演算子&を適用した&Xは,Type *型のポインタであり,その値はxのアドレスである.

間接演算子

ポインタに間接演算子*を適用すると,それが指すオブジェクトそのものを表します.
*a aが指すオブジェクト
ポインタpがxを指すとき,*pはxのエイリアス(別名)となる.

Type x;
Type *p;

p = &x;

printf("%d", *p)

関数の引数としてのポインタ

#include <stdio.h>

//ポインタの引数はこう
void swap(int *px, int *py)
{
    int temp = *px;
    *px = *py;
    *py = temp;
}

void sort(int *n1, int *n2)
{
    if (*n1 > *n2)
        swap(n1,n2);
}


int main(void)
{
    int na,nb;

    puts("2つの整数を入力してください.");
    printf("整数A:"); scanf("%d", &na);
    printf("整数B:"); scanf("%d", &nb);

    //渡し方はこう&をつける
    sort(&na,&nb);
    printf("%d,%d", na,nb);

    return 0;
}

上のように書きます.
*swap(n1,n2);とかきます.swap(&n1,&n2);ではないです.
&n1&n2の型は,intへのポインタへのポインタ型となるかららしい.

5
4
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
5
4