0%

函数指针

1
void func(int a,int b , int (*func2)(int x, int y));

函数指针function pointer通常应用于菜单驱动的系统中。系统提示用户从菜单中选择一种操作,每个选项的操作都是由不同过的函数来完成的。指向每个函数的指针就存储在一个指针数组中。用户的选择将作为数组的下标,并且数组中的指针被用于调用相应的函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <stdio.h>

void function1(int a, int b);
void function2(int a, int b);
void function3(int a, int b);

int main(void)
{
void (*f[3])(int ,int) = {function1,function2,function3};
int choice;


printf("Enter a number between 0 and 2, 3 to end:");
scanf("%d",&choice);

while(choice >= 0 && choice < 3)
{
(*f[choice])(choice);
printf("Enter a number between 0 and 2, 3 to end:");
scanf("%d",&choice);
}

printf("Program execution completed.\n");
return 0;
}

void function1(int a, int b)
{
printf("You are now using function1");
}

void function2(int a, int b)
{
printf("You are now using function1");
}

void function3(int a, int b)
{
printf("You are now using function1");
}

函数形参为const

如果一个变量作为实参传递给一个函数,并且这个变量没有也不应该在这个函数体中被修改,那么应该将这个变量声明为const,以避免其被意外改写,比如:

1
extern char *strcpy(char dest[],const char *src);

这个函数我们可以保证src肯定不能被修改的。

const的含义

  • const char *p:p为指向字符常量的指针
  • char const *p:p为指向字符常量的指针
  • char * const p:声明一个指向字符的指针常量p

little-endian和big-endian区别

endian一词源于小说格列佛游记,小说中,小人国为水煮蛋从大的一段big-end还是小的一端little-end剥开而争论(我习惯从大端打开clip_image001),争论的双方分别被称为big-endians和little-endians。

对于字节序的典型情况为整数在内存中的存放方式和网络传输的传输顺序

  • 小端序:LSByte在MSByte的前面,即LSB为低地址,MSB为高地址;
  • 大端序:MSByte在LSByte的前面,即LSB为高地址,MSB为低地址;

对于单一的字节,大部分处理器以相同的顺序处理位元bit,因此单字节的存放方法和传输方式一般相同。