Last active
March 6, 2021 05:14
-
-
Save KeitetsuWorks/5d65dd731b53169e28107f17bc623b18 to your computer and use it in GitHub Desktop.
動的メモリ確保のサンプルプログラム
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @file jugyoin.cpp | |
* @brief 動的メモリ確保のサンプルプログラム | |
* @author Keitetsu | |
* @date 2017/06/14 | |
* @copyright Copyright (c) 2017 Keitetsu | |
*/ | |
#include <iostream> | |
using namespace std; | |
/** | |
* @struct jyugyoin_st | |
* @brief 従業員情報格納用構造体 | |
* | |
* @typedef JUGYOIN_T | |
* @brief 従業員情報格納用構造体 | |
*/ | |
typedef struct jugyoin_st { | |
int number; /**< 社員番号 */ | |
char shimei[80]; /**< 氏名 */ | |
long kyuyo; /**< 給与額 */ | |
} JUGYOIN_T; | |
/** | |
* @brief 従業員情報を標準出力に表示する | |
* @param[in] p 従業員情報格納用構造体のポインタ | |
*/ | |
void showJugyoin(JUGYOIN_T *p); | |
/** | |
* @brief 従業員情報を格納するメモリ領域を確保し、 | |
* 標準入力から従業員情報を取得する | |
* @return 従業員情報格納用構造体のポインタ | |
*/ | |
JUGYOIN_T *getJugyoin(void); | |
/** | |
* @brief メイン関数 | |
* @retval 0 正常終了 | |
* @retval 1 異常終了 | |
*/ | |
int main(void) | |
{ | |
// 従業員情報格納用構造体のポインタ | |
JUGYOIN_T *p; | |
// 従業員情報を格納するメモリ領域を確保し、 | |
// 標準入力から従業員情報を取得する | |
// (関数の戻り値はポインタ) | |
p = getJugyoin(); | |
// 従業員情報を標準出力に出力する | |
// (ポインタ渡し) | |
showJugyoin(p); | |
// メモリ領域を解放する | |
delete p; | |
return 0; | |
} | |
JUGYOIN_T *getJugyoin(void) | |
{ | |
// 構造体のポインタを宣言する | |
JUGYOIN_T *p; | |
// 構造体の実体(メモリ領域)を確保する | |
p = new JUGYOIN_T; | |
// 構造体のメンバに代入を行う | |
cout << "社員番号を入力して下さい" << endl; | |
cin >> p->number; | |
cout << "氏名を入力して下さい" << endl; | |
cin >> p->shimei; | |
cout << "給与額を入力して下さい" << endl; | |
cin >> p->kyuyo; | |
// 構造体のポインタを返す | |
return p; | |
} | |
void showJugyoin(JUGYOIN_T *p) | |
{ | |
// 構造体のポインタを使ってメンバを表示する | |
cout << "社員番号: " << p->number << endl; | |
cout << "氏名: " << p->shimei << endl; | |
cout << "給与額: " << p->kyuyo << endl; | |
return; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment