構造体とポインタ

スポンサーリンク
スポンサーリンク
ライフスタイル関連のコンテンツ
お金 | 仕事 | 勉強 | プライベート | 健康 |
プログラミング関連のコンテンツ
C言語/C++入門 | Ruby入門 | Python入門 | プログラミング全般

構造体の配列もポインタで扱うことができ、配列の場合と同様です。

スポンサーリンク

#include <string>
#include <iostream>
 
struct profile {
    std::string name;        // 名前
    int tel;                // 電話番号
    int old;                // 年齢
};
 
int main() {
    int i;
    struct profile friends[10] = {
        {"Tom", 123, 35},
        {"Bill", 456, 27},
        {"Jack", 789, 19},
    };
 
    struct profile *friends_ptr[10];    // 構造体配列のデータへのポインタ宣言
 
    for (i = 0; i < 3; i++) {
        friends_ptr[i] = &friends[i];
        std::cout << friends_ptr[i] << ": " << friends_ptr[i]->name << ", " << friends_ptr[i]->old << "\n";
    }
 
    return 0;
}

構造体へのポインタを参照するためには、「構造体へのポインタ->メンバ名」とアロー演算子「->」を用います。
実行結果。

0012F1F4: Tom, 35
0012F21C: Bill, 27
0012F244: Jack, 19
スポンサーリンク
 
スポンサーリンク