#include <stdio.h>
#include <stdlib.h>
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("%d\n%d\n", ((str *)p)->a, ((str *)p)->b);
st1 = (str *)p;
printf("%d\n%d\n", st1->a, st1->b);
free(st);
return 0;
}
图 一
c语言的void指针指向的具体指针,必须强制转换
如图一的
# include <stdio.h>
# include<stdlib.h>
# include <string.h>
typedef struct
{
int year;
int month;
int day;
} AGE;
typedef struct
{
char name[20]; //姓名
int num; //学号
void *birthday; /*用struct AGE结构体类型定义结构体变量birthday, 生日*/
float score; //分数
} STUDENT;
int main(void)
{
STUDENT student1; /*用struct STUDENT结构体类型定义结构体变量student1*/
STUDENT *p = NULL; /*定义struct STUDENT结构体类型的指针变量p*/
p = &student1; /*p指向结构体变量student1的首地址, 即第一项的地址*/
strcpy(p->name, "小明");
printf("birth is %x\n", p->birthday);
AGE *bd;
bd = ( AGE *) malloc(sizeof(AGE));
printf("sizeof AGE is %d\r\n", sizeof(AGE));
printf("sizeof STUDENT is %d\r\n", sizeof(STUDENT));
bd->day = 29;
bd->year = 1989;
bd->month = 3;
p->birthday = bd;
p->num = 1207041;
p->score = 100;
printf("name : %s\n", p->name); //p->name不能写成p
printf("birthday : %d-%d-%d\n", ((AGE *)p->birthday)->year, ((AGE *)p->birthday)->month, ((AGE *)p->birthday)->day);
printf("num : %d\n", p->num);
printf("score : %.1f\n", p->score);
return 0;
}
图二
图二的
也是强制转行