c语言void指针

#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;
}

图二

图二的

 也是强制转行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值