アプリ版:「スタンプのみでお礼する」機能のリリースについて

C言語初心者です。
よろしくお願い致します。

1 #include <stdio.h>
2
3 struct Animal {
4 int eyes;
5 double weight;
6 };
7
8 // 構造体のポインタ変数を引数に取る関数(2)
9 void func2(struct Animal* panimal) {
10 printf("func2: eyes[%d]\n", panimal->eyes);
11 printf("func2: weight[%f]\n", panimal->weight);
12 }
13
14 // 構造体のポインタ変数を引数に取る関数(1)
15 void func1(struct Animal* panimal) {
16 printf("func1: eyes[%d]\n", panimal->eyes);
17 printf("func1: weight[%f]\n", panimal->weight);
18 func2(panimal); // アドレス(ポインタ)を渡す
19 }
20
21 int main(void) {
22 struct Animal animal = { 2, 54.3 };
23
24 func1(&animal); // アドレス(ポインタ)を渡す
25 // eyes[2]
26 // weight[54.300000]
27
28 return 0;
29 }

(※参考)https://yu-nix.com/blog/2021/11/1/c-struct-point …

上記プログラムを実行すると、
func1: eyes[2]
func1: weight[54.300000]
func2: eyes[2]
func2: weight[54.300000]
画面表示されます。

18行 func2(panimal); の引数ですが、
もしも、引数に&を入力して
func2(&panimal);
とした場合でも、上記実行結果を得る方法はあるのでしょうか?

(構造体のポインタ変数)の&とは?

A 回答 (3件)

やってみれば解る。

    • good
    • 0

&変数 は、変数のアドレスを取得することを意味します。


24行目のfunc1(&animal);
はamimlのアドレス(=ポインター)を取得し、その値を引数として渡しています。

18行目でfunc2(&panimal);とすると

panimalのアドレスを取得します。panimalはポインターなので、
そのポインターのアドレスを渡すことになり、おかしくなります。

>もしも、引数に&を入力して
>func2(&panimal);
>とした場合でも、上記実行結果を得る方法はあるのでしょうか?

その場合、func2をポインターへのポインターが渡されるように変える必要があります。
下記がfunc2をそのように変えたサンプルです。(実用性はありません)

#include <stdio.h>

struct Animal {
int eyes;
double weight;
};

// 構造体のポインタ変数を引数に取る関数(2)
void func2(struct Animal** ppanimal) {
struct Animal* panimal = *ppanimal;
printf("func2: eyes[%d]\n", panimal->eyes);
printf("func2: weight[%f]\n", panimal->weight);
}

// 構造体のポインタ変数を引数に取る関数(1)
void func1(struct Animal* panimal) {
printf("func1: eyes[%d]\n", panimal->eyes);
printf("func1: weight[%f]\n", panimal->weight);
func2(&panimal); // アドレス(ポインタ)を渡す
}

int main(void) {
struct Animal animal = { 2, 54.3 };

func1(&animal); // アドレス(ポインタ)を渡す
// eyes[2]
// weight[54.300000]

return 0;
}
    • good
    • 0

No2です。


func2は以下のようにしても構いません。

void func2(struct Animal** ppanimal) {
printf("func2: eyes[%d]\n", (*ppanimal)->eyes);
printf("func2: weight[%f]\n", (*ppanimal)->weight);
}

参考までにポインターの図です。
「構造体のポインタを引数に取る関数」の回答画像3
    • good
    • 0
この回答へのお礼

ズバリ回答ありがとうございました。
ポインターの図も示して頂いたお陰で、理解が深まりました。

お礼日時:2022/01/23 21:45

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!