NO.5 指针

(一)使用未初始化的指针(uninitialized pointer)

[cpp] view plain copy
int main(void)  
{  
  int x, *p;    
  x = 10;  
  *p = x; //错误,指针未初始化   
  return 0;  
}  
上述程序将值10写到未知的内存位置,因为从未向指针p赋值,p的内容不确定。


(二)误解指针的用法,将值当做地址赋给指针

[cpp] view plain copy
#include <stdio.h>  
int main(void)  
{  
  int x, *p;  
  x = 10;  
  p = x;    //错误,应该是p=&x,指针保存的是地址,而不是值   
  printf("%d", *p);  
  return 0;  
}  


(三)这种错误是对内存中数据存放位置的错误假定。比较指向不同对象的指针时,容易产生意外结果。例如:

[cpp] view plain copy
char s[80], y[80];  
char *p1, *p2;  
p1 = s;  
p2 = y;  
if(p1 < p2) . . .    //错误,不能确保数据处于内存的同样位置,也不能确保各种机器都用同样的格式保存数据。
类似的错误是想当然地以为同时定义的两个数组在内存区是顺序排列,从而简单地对指针增值,期望像使用两者组成的一个数组那样跨越数组边界。例如:
[cpp] view plain copy
int first[10], second[10];  
int *p, t;  
p = first;  

for(t=0; t<20; ++t)  *p++ = t;  

(四)

[cpp] view plain copy

/* 这段程序有错误 */  
#include <string.h>  
#include <stdio.h>  
  
int main(void)  
{  
  char *p1;  
  char s[80];  
  p1 = s;  
  do {  
    gets(s);  /* read a string */  
  
    /* print the decimal equivalent of each 
       character */  
    while(*p1) printf(" %d", *p1++);  
  
  } while(strcmp(s, "done"));  
  
  return 0;  
}  
上述程序通过p1打印出与s中诸字符关联的ASCII值。问题是只对p赋值(s的地址)一次。第一轮循环中,p1指向s中首字符。第二轮循环时,因为未再置成s的起点,p值从第一轮的结束点继续。此时,p可能指向另一个串,另一个变量,甚至程序的某一段。正确程序应该是:
[cpp] view plain copy
#include <string.h>  
#include <stdio.h>   
  
int main(void)  
{  
  char *p1;  
  char s[80];  
  
  do {  
    p1 = s; /* reset p1 to beginning of s */  
    gets(s);  /* read a string */  
  
    /* print the decimal equivalent of each 
       character */  
    while(*p1) printf(" %d", *p1++);  
  
  } while(strcmp(s, "done"));  
  
  return 0;  
}  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值