结构体中的指针成员应用案例

发布时间:2022-07-06编辑:zhushican阅读(297)

【案例描述】

纠正下面代码中的语法错误。

#include<stdio.h>;

main()

{ struct Lb{int n;Lb *p;}*t,*h=0;

  int n;

  for(n=0;n<4;n++)

  {  t=malloc(Lb);

     scanf("%d",t.n);

     if(h==0)h=t;

     else {t.p=h;h=t;}

  }

  printf("%d",h.n);}

结构体中的指针成员应用案例

【案例分析】

1、预处理命令不是语句,不能以分号结尾

2、定义结构体变量时,不能缺省struct关键字

3、使用malloc函数动态申请内存空间时,参数是申请内存的字节数

4、malloc函数返回值为void*指针,需转换类型后再赋值给指针变量

【参考代码】

main()

{ struct Lb{int n;struct Lb *p;}*t,*h=0;

  int n;

  for(n=0;n<4;n++)

  {  t=(struct Lb *)malloc(sizeof(struct Lb));

  scanf("%d",&t->n);

      if(h==0)h=t;

  else {t->p=h;h=t;}

  }

  printf("%d",h->n);

}


评论