zoukankan      html  css  js  c++  java
  • 含有指针变量的结构体的指针的应用

      代码如下:

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <string.h>
     4
     5 typedef struct _student{
     6     char *name;
     7     short id;
     8     double record;
     9     char sex;
    10 } Student;
    11
    12 Student *initStudent(int i){
    13     Student *ptrStu = (Student *)malloc(sizeof(Student));
    14     ptrStu->name = (char *)malloc(sizeof(char) * 20);
    15     printf("Input the %d'th student info: 
    ", i + 1);
    16     printf("name: ");
    17     scanf("%s", ptrStu->name);
    18     printf("id: ");
    19     scanf("%d", &ptrStu->id);
    20     printf("record: ");
    21     scanf("%lf", &ptrStu->record);
    22     int tmp = getchar();
    23     printf("sex: ");
    24     scanf("%c", &ptrStu->sex);
    25
    26     return ptrStu;
    27 }
    28
    29 void deleteStudent(Student *ptrStu){
    30     free(ptrStu->name);
    31     free(ptrStu);
    32
    33     return;
    34 }
    35
    36 void displayStudent(Student *ptrStu){
    37     printf("The student %s's info:	", ptrStu->name);
    38     printf("name: %s	", ptrStu->name);
    39     printf("id: %d	", ptrStu->id);
    40     printf("record: %lf	", ptrStu->record);
    41     printf("sex: %c
    ", ptrStu->sex);
    42
    43     return;
    44 }
    45
    46 int main(int argc, char **argv)
    47 {
    48     int size;
    49     printf("please input the size: ");
    50     scanf("%d", &size);
    51     Student *arrStudent[size];
    52     for(int i = 0; i < size; i++){
    53         arrStudent[i] = initStudent(i);
    54     }
    55     for(int i = 0; i < size; i++){
    56         displayStudent(arrStudent[i]);
    57     }
    58     for(int i = 0; i < size; i++){
    59         deleteStudent(arrStudent[i]);
    60     }
    61     printf("test finished!
    ");
    62
    63     return 0;
    64 }

      代码说明:

        (1)、第5-10行代码定义了结构体Student,成员变量name是char *型, record是double型;

        (2)、第12行代码函数initStudent()完成结构体Student *的初始化;

        (3)、第13行代码为结构体指针ptrStu申请内存空间;

        (4)、第14行代码为指针ptrStu的成员指针name申请内存空间

        (5)、第21行代码scanf("%lf", &ptrStu->record),务必注意double数据类型的数据输入的占位符是lf;

        (6)、第22行代码int tmp = getchar()将上边输入内容后的回车字符去掉;

        (7)、第29行代码函数deleteStudent()释放结构体指针,注意释放顺序;

        (8)、第36行代码函数displayStudent()输出指定结构体指针ptrStu的内容;

        (9)、第46行代码函数main()中完全遵照,申请内存,使用内存,释放内存的步骤使用内存;

  • 相关阅读:
    关于使用MySQL语法ON DUPLICATE KEY UPDATE单个增加更新及批量增加更新的sql
    关于ESB(企业服务总线)
    [SoapUI] 在SoapUI中通过Groovy脚本执行window命令杀掉进程
    [SoapUI] 判断工程下某个文件是否存在,存在就删除
    [OpenCV-Python] OpenCV-Python 中文教程
    [Robot Framework] Jenkins上调用Rebot命令时执行报错不往下执行其他命令
    如何让程序在开机时自动启动
    @1-5使用pandas保存豆瓣短评数据
    @1-4使用Xpath解析豆瓣短评
    @1-2初识Python爬虫
  • 原文地址:https://www.cnblogs.com/guochaoxxl/p/7666010.html
Copyright © 2011-2022 走看看