《征服C指针》笔记

来源:互联网 发布:云计算怎么开公司啊 编辑:程序博客网 时间:2024/06/16 06:16

指针初步

  • 指针类型由标量和组合类型派生,有指针类型变量、指针类型的值(内存地址)之分。
  • void*是可以指向任何类型的指针类型,在ANSI C可以不强制转型赋值给所有变量。
  • 指针运算:对指针加N,指针前进“当前指针指向的数据类型的长度xN”。
  • 数组和指针:在表达式中数组名可以被解读为指针,本质上是&array[0]。
    • array[i]是*(array+i)的简便写法。
    • void func(int a[]) 解读为 void func(int* a)
    • void func(int a[][5]) 解读为 void func(int (*a)[5])
    • h[i][j] 等同 ((hoge + i))[j] 等同 ((*(hoge +i)) + j)

C如何使用内存

(函数【程序本身】、字符串常量)(静态变量【函数内static变量、文件内static变量、全局变量】)(malloc分配的内存<堆>)(......)(自动变量<栈>,参数从后往前堆积)
  • malloc()

    • 返回void*类型,free()后对应内存区不会被马上破坏
    • void* calloc(size_t nmemb, size_t size);
    • p = malloc(nmemb * size); memset(p, 0, nmemb * size);
    • void* realloc(void* ptr, size_t size);
  • 内存布局对齐,常见在结构体中,int占4字节,char也占4字节(实际有效占1字节)

  • 字节排序(Byte Order):0x12345678
    • 小端字节:(上)78,56,34,12(下)
    • 大端字节:(上)12,34,56,78(下)

C的声明

  • 指针解读顺序:标识符->派生类型(括弧()、数组[]、函数()、指针*)->数据类型修饰符
int (*func_p)(double)- func_p is- func_p is pointer to- func_p is pointer to function(double) returning- func_p is pointer ot function(double) returning int
  • const修饰符解读顺序:从标识符开始由内往外解释,一旦解释完毕部分左侧出现const,在当前为追加read-only。(const修饰紧跟在它后面的单词)
char* const src;- src is read-only pointer to charchar const * src;- src is pointer to read-only char
  • typdef解读顺序:先分解,后组合
typdef char* string; string hoge[10];- string is pointer to char; hoge is array of string;- hoge is array of pointer to char;
0 0