#include#include typedef struct { int a; int b; } str; int main(int argc, char *argv[]) { void *p; str *st, *st1; st = (str *)malloc(sizeof(str)); st->a = 23; st->b = 24; p = st; printf("%dn%dn", ((str *)p)->a, ((str *)p)->b); st1 = (str *)p; printf("%dn%dn", st1->a, st1->b); free(st); return 0; }
图 一
c语言的void指针指向的具体指针,必须强制转换
如图一的
# include# include # include typedef struct { int year; int month; int day; } AGE; typedef struct { char name[20]; //姓名 int num; //学号 void *birthday; float score; //分数 } STUDENT; int main(void) { STUDENT student1; STUDENT *p = NULL; p = &student1; strcpy(p->name, "小明"); printf("birth is %xn", p->birthday); AGE *bd; bd = ( AGE *) malloc(sizeof(AGE)); printf("sizeof AGE is %drn", sizeof(AGE)); printf("sizeof STUDENT is %drn", sizeof(STUDENT)); bd->day = 29; bd->year = 1989; bd->month = 3; p->birthday = bd; p->num = 1207041; p->score = 100; printf("name : %sn", p->name); //p->name不能写成p printf("birthday : %d-%d-%dn", ((AGE *)p->birthday)->year, ((AGE *)p->birthday)->month, ((AGE *)p->birthday)->day); printf("num : %dn", p->num); printf("score : %.1fn", p->score); return 0; }
图二
图二的
也是强制转行
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)