您的位置:首页 > 其它

结构体和函数指针

2015-12-13 13:56 204 查看
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\n", a);

}

void funB(int a){

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

}

void funC(int a){

printf("a*%d\n", 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

在定义结构体的时候,结构体里面的变量必须是能够明确确定内存空间的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: