【【Allen5G】C语言学习第20篇---指针的本质剖析】https://toutiao.com/group/6696238353186030087/?app=explore_article×tamp=1566537702&req_id=201908231321420100180260463127622&group_id=6696238353186030087&tt_from=copy_link&utm_source=copy_link&utm_medium=toutiao_ios&utm_campaign=client_share *号的意义 在指针声明时,*号表示所声明的变量为指针 在指针使用时,*号表示取指针所指向的内存空间中的值 我将其理解为“钥匙”,如图 实例1:指针使用 #include <stdio.h> int main(){ int i = 0; int* pI; char* pC; float* pF; pI = &i; *pI = 10; printf('%p, %p, %d\n', pI, &i, i); printf('%d, %d, %p\n', sizeof(int*), sizeof(pI), &pI); printf('%d, %d, %p\n', sizeof(char*), sizeof(pC), &pC); printf('%d, %d, %p\n', sizeof(float*), sizeof(pF), &pF); return 0;} 传值调用和传址调用
实例2:利用指针交换变量 #include <stdio.h> int swap(int* a, int* b){ int c = *a; *a = *b; *b = c;} int main(){ int aa = 1; int bb = 2; printf('aa = %d, bb = %d\n', aa, bb); swap(&aa, &bb); printf('aa = %d, bb = %d\n', aa, bb); return 0;} 常量与指针 (这个意思是说怎么分辨是指针还是常量) 方法是:左数右指 当const出现在*号左边时指针指向的数据为常量 当const出现在*后右边时指针本身为常量 实例3:常量与指针分析 #include <stdio.h> int main(){ int i = 0; const int* p1 = &i; int const* p2 = &i; int* const p3 = &i; const int* const p4 = &i; *p1 = 1; // compile error p1 = NULL; // ok *p2 = 2; // compile error p2 = NULL; // ok *p3 = 3; // ok p3 = NULL; // compile error *p4 = 4; // compile error p4 = NULL; // compile error return 0;} 小结:
|
|
来自: 山峰云绕 > 《C语言数据结构描述Windows程序设计》