//--------------------------------------- // // // C++でのメモリの動的確保 // // //--------------------------------------- //■Update 2016/6/4 // アドレス参照機能の追加 // // //-------------------------------------- // includefile //-------------------------------------- #include #include //-------------------------------------- // マクロ定義 //-------------------------------------- #define _SHOW_ADDRESS //アドレス参照機能の有効化 #undef _SHOW_ADDRESS //アドレス参照機能の無効化 //-------------------------------------- // 定数定義 //-------------------------------------- #define MAX_NAME (64) //名前の最大文字数 //------------------------------------- // struct //------------------------------------- //player構造体 typedef struct{ char aName[MAX_NAME]; //playerの名前 int nLife; //playerのライフ int nAttack; //playerの攻撃力 int nSpeed; //playerの速さ }PLAYER; ////////////////////////////////////// //メイン関数 void main ( void ) { PLAYER *pPlayer; //データ pPlayer=NULL; int player; printf("何人のデータを用意しますか? > "); scanf("%d",&player); pPlayer = (PLAYER*)malloc( sizeof(PLAYER) * (player) ); //メモリ確保 if(pPlayer == NULL){ printf("メモリの確保に失敗しました"); } //アドレスの格納番地の参照 #ifdef _SHOW_ADDRESS for(int count=0; count < player; count++) { printf("アドレス[%d] : %p \n",(count+1),&pPlayer+count); } #endif //データを入力 printf("< 入力 >\n"); for(int count=0; count < player; count++){ printf("名前 :"); scanf("%s",&pPlayer[count].aName[0]); rewind(stdin); printf("攻撃 :"); scanf("%d",&pPlayer[count].nAttack); rewind(stdin); printf("ライフ :"); scanf("%d",&pPlayer[count].nLife); rewind(stdin); printf("スピード :"); scanf("%d",&pPlayer[count].nSpeed); rewind(stdin); } //データを出力 printf("< 出力 >\n"); for(int count=0; count < player; count++){ printf("pPlayer Name : %s\n",&pPlayer[count].aName[0]); printf("pPlayer Attack : %d\n",pPlayer[count].nAttack); printf("pPlayer Life : %d\n",pPlayer[count].nLife); printf("pPlayer Speed : %d\n",pPlayer[count].nSpeed); } //キー待ち rewind(stdin); getchar(); //終了処理 free(pPlayer); //メモリの開放(☆重要☆) pPlayer=NULL; //アドレスの消去(☆重要☆) }