zoukankan      html  css  js  c++  java
  • 结构体和函数指针

    1、简单结构体

    struct student{

      char name[20];   //可以用scanf或者直接赋值     

        *如果用char *name  在用scanf时没有内存接收

      long id;

      int age;

      float height;

    };

    结构体中只能声明变量不能赋初值。

    struck student zhangsan;

    struck student zhangsan = {"xiaowang",2000002,20,180.5};

    结构体的访问用".":xiaowang.name

    2、typedef

    typedef  struct student{

      char name[20];   //不能用char *name  在用scanf时没有内存接收

      long id;

      int age;

      float height;

    }Student;     // typedef给一个存在的类型取一个别名

    Student zhangsan;

    Student zhangsan = {"xiaowang",2000002,20,180.5};

    如果不加typedef:

    struct student{

      char name[20];   //不能用char *name  在用scanf时没有内存接收

      long id;

      int age;

      float height;

    }Student;//Student 是一个变量了

    3、结构体指针

    Student *s;

    如果*name是字符串      s->name = "xiaowang";

    如果name[]是数组接收  strcpy(s->name,"xiaowang");

    s->age = 23;

    Student *s[5]; //每一块都存着结构体的地址

    Student xw ={"xiaowang",2345,23,164.3};

    s[0] =&xw;  //结构体指针数组里面的每一个都存着地址,如果不给他内存地址,它的值就为空,不可直接赋值。

    s[0]->age = 20;

    4、结构体数组

    Student array[5] ={};

    strcpy(array[0].name,"xiaowang");

    array[0].age = 23;

    5、用函数指针实现回调(block)功能

    #include <stdio.h>

    int add(int a, int b, void (*pFunction)(int)){

        //。。。。。

        pFunction(a+b);

        return a + b;

    }

    void funA(int a){

        printf("a+%d ", a);

    }

    void funB(int a){

        printf("a-%d ", a);

    }

    void funC(int a){

        printf("a*%d ", a);

    }

    int main(int argc, const char * argv[]) {

        //一个函数指针只能指向一种类型的函数

        void (*pFunction[3])(int);

        

        pFunction[0] = funA;

        pFunction[1] = funB;

        pFunction[2] = funC;

        

        for (int i = 0; i < 3; i++) {

            pFunction[i](3);

        }

        return 0;

    }

    计算结构体内存空间

    原理:如果结构体内部拥有多种数据类型,那么以占据内训字节数最高的类型对齐

    typedef  struct{

      char *name;

      int age;

    }Persong;//16

    char *占据8个字节,int占据4个字节

    所以age变量自动向name对齐,整个占据16个字节

    typedef  struct{

      char name;

      int age;

    }Person;//8

    typedef  struct{

      char name[2];

      int age;

    }Person;//8

    typedef  struct{

      char name[6];

      int age;

    }Person;//12

    在定义结构体的时候,结构体里面的变量必须是能够明确确定内存空间的

  • 相关阅读:
    51CTO资料索引 很不错
    extern和extern“c"作用详解 以及C和C++混合编程 在文章:3.深层揭密extern "C" 部分可以看到 .
    用VC++实现图像检索技术(转)
    OpenSceneGraph FAQ
    NeHe OpenGL教程 02 渲染第一个多边形
    C++经验谈(摘抄)
    利用条件编译实现工程定制版本的自动输出
    没有文件扩展".js"的脚本引擎 解决办法
    OpenGL FAQ
    NeHe OpenGL教程 01 创建OpenGL窗口
  • 原文地址:https://www.cnblogs.com/zhaopengs/p/5042649.html
Copyright © 2011-2022 走看看