搜尋此網誌

[C/C++][Structure Pointer]

對變數 student 其中的成員取用為 s.name
若用指標方法存取 student *ps,則必須使用箭頭 ps->name

/*
* File Name: StructurePointer.cpp
* Author: MH
* Since 2013/04/01
* Toolkit: Dev C++ 4.9.9.9
*/

#include <stdio.h>

struct student{

    char name[4];
    int id;
    float gpa;

};

int main(){

    struct student s = {"Sam", 9732, 3.5};
    struct student *ps = &s;
    // ps: a pointer pointing to structure variable s

    struct student &rs = s;
    // rs: a reference variable, it is an alias of s

    printf("%s %d %f\n", s.name, s.id, s.gpa);
    printf("%s %d %f\n", ps->name, ps->id, ps->gpa);
    printf("%s %d %f\n", rs.name, rs.id, rs.gpa);

    return 0;
}

沒有留言:

張貼留言