学習中、以下のような構造体の使い方を学びました。
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef void (*fptrPrint)(); typedef struct _functions{ fptrPrint display; } stFunc; void justPrint(){printf("%s\n", "aaaaaaaaaaa");} typedef struct aa{ int a; int b; int c; int c2; stFunc functions; }aa; typedef struct bb{ aa base; }bb; aa* getaaInstance(); aa* getaaInstance(){ aa *aap = (aa*)malloc(sizeof(aa)); aap->functions.display = justPrint; return aap; } bb* getbbInstance(); bb* getbbInstance(){ bb *bbp = (bb*)malloc(sizeof(bb)); bbp -> base.functions.display = justPrint; // <=この行ないと、Segmentation fault return bbp; } int main(int argc, char** argv){ aa* aaplist[2]; aaplist[0] = getaaInstance(); aaplist[0] -> functions.display(); aaplist[1] = getbbInstance(); aaplist[1] -> functions.display(); return 0; }
自分にはなぜ、
aaplist[1] -> functions.display();
ができてしまうのか理解できません。
bbp -> base.functions.display = justPrint;
という行がないとエラーとなりますので、ここが重要な役割をしているのは理解できるのですが...
aaplist[1] = getbbInstance();
という行でaa構造体ポインタに対してbb構造体を代入しているので、functionsメンバも生きているのでそれに関数ポインタを入れている???
もちろん、aaplist[1] -> base.functions.display();はbaseというメンバはbb構造体にはないのでできないことは理解しております。
なにか手がかりを頂ければ助かります。
回答3件
あなたの回答
tips
プレビュー