LoginSignup
0
0

More than 1 year has passed since last update.

【C言語】ポインタ渡し

Last updated at Posted at 2021-07-11

ポインタ渡しとは

ポインタ渡しは変数のメモリ上のアドレスを渡す記法である. 値渡しとは異なり, 渡されたアドレスを間接参照する事で, 関数の呼び出し元の変数を書き換える事が出来ます。

端的に言えば他の関数に変数の値を渡したいとき、変数の値ではなくアドレスを渡してしまえば、渡す前の関数と渡した後の関数とでは変数のアドレスが同じなる。つまり同一メモリ上の変数を扱っていることなのです。

文字列の扱いについて

C言語の文字列は配列によって扱われる。配列の文字列そのものをすべて他の関数に引数として渡すことができないです。※構造体にすれば渡すことが可能。
試してみましょう。

やりたいことは
配列monthdateの中の値をget_birthday関数に渡し出力する処理です。

下記のソースではコンパイルエラーになります。

引数の型が違うので当然エラーがでます。

sample.c
#include <stdio.h>

int get_birthday(char ,char);

int get_birthday(char recv_month,char recv_date)
{
    printf("私の誕生日は%s月%s日です",recv_month,recv_date);
    return 0;
}

int main(void)
{
    char month[] = {"08"};
    char date[]  = {"12"};

    get_birthday(month,date);

    return 0;
}



配列すべてを渡せないないので変数のアドレス受け取って参照します。

sample.c
#include <stdio.h>

int get_birthday(char* ,char *);

int get_birthday(char* recv_month,char *recv_date)
{
    printf("私の誕生日は%s月%s日です\n",recv_month,recv_date);

    return 0;
}

int main(void)
{
    char month[] = {"08"};
    char date[]  = {"12"};

    get_birthday(month,date);

    return 0;
}

厳密にいえば配列の先頭アドレスを渡しています。

sample.c
#include <stdio.h>

int get_birthday(char* ,char *);

int get_birthday(char* recv_month,char *recv_date)
{

    printf("私の誕生日は%s月%s日です\n",recv_month,recv_date);
    return 0;
}

int main(void)
{
    char month[] = {"08"};
    char date[]  = {"12"};

    get_birthday(&month[0],&date[0]);

    return 0;
}

C言語では頻繁に使用しますね。
今回は配列のアドレスを使いましたが構造体でも使えるので非常便利です。

以上

0
0
2

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