C语言指针使用技巧

来源:互联网 发布:金属材料牌号查询软件 编辑:程序博客网 时间:2024/05/17 18:15

1、指针在本质上也是一个变量;

2、指针需要占用一定的内存空间;
3、指针用于保存内存地址的值
;
不同类型的指针占用的内存空间大小相同,可以通过以下例子看出:

 

  1. #include <stdio.h>

  2. int main()
  3. {
  4.     int i;
  5.     int* pI;
  6.     char* pC;
  7.     float* pF;
  8.     
  9.     pI = &i;
  10.     
  11.     printf("%d, %d, %0X\n", sizeof(int*), sizeof(pI), &pI);
  12.     printf("%d, %d, %0X\n", sizeof(char*), sizeof(pC), &pC);
  13.     printf("%d, %d, %0X\n", sizeof(float*), sizeof(pF), &pF);
  14.     
  15.     return 0;
  16. }


程序运行结果如下:

  1. lihacker@lihacker-laptop:/mnt/share/c$ ./a.out
  2. 4, 4 BF89351C
  3. 4, 4 BF893518
  4. 4, 4 BF893514

       

常量指针变量指针

 

  1. const int* p; //p可变,p指向的内容不可变
  2. int const* p; //p可变,p指向的内容不可变
  3. int* const p; //p不可变,p指向的内容可变
  4. const int* const p;//p和p指向的内容都不可变

口诀:左数右指
const出现在*号左边时指针指向的数据为常量

const出现在*后右边时指针本身为常量


  1. #include <stdio.h>

  2. int main()
  3. {
  4. int i = 0;
  5. const int* p = NULL;
  6.  p = &i;
  7.  
  8. *= 10;
  9.  
  10.  return 0;
  11.  }

编译时会报错:

  1. lihacker@lihacker-laptop:/mnt/share/c$ gcc test1.
  2. test1.c: In function ‘main’:
  3. test1.c:10: error: assignment of read-only location ‘*p’

此时说明第10行语句:*p = 10 出错。

0 0
原创粉丝点击