11.構造体

11-15. 構造体ポインタ関数

◇構造体ポインタ関数

 これは、戻り値を構造体のアドレスとするものです。ポインタ関数の発展版みたいなものです。

 それでは上のプログラムを改造してみます。

#include<stdio.h>

struct st_samp{
    int x;
    int y;
    int z;
};

struct st_samp *p_output(struct st_samp st);

main()
{

    struct st_samp s1={2,3,0};
    struct st_samp *p_st;

    p_st = p_output(s1);

    printf("%d * %d = %d\n",p_st->x,p_st->y,p_st->z);
    return;
}

struct st_samp *p_output(struct st_samp st)
{
    st.z = st.x * st.y;
    return &st;
}

/* 結果
2 * 3 = 6
*/

main()
s1 st
┌────┐ ┌────┐
│s1.x ├──→│st.x │←┐p_st->x
├────┤ ├────┤ │
│s1.y ├──→│st.y │←┤p_st->y
├────┤ ├────┤ │
│s1.z ├──→│st.z │←┤p_st->z
└────┘ └─┬──┘ │
┌───────┘ │
↓ return &st │
┌────┐ │
│&st ├──────────┘
└────┘

次章
12.基本ライブラリ