"The Complete Reference C" 读书笔记

"The Complete Reference C"
一.指针常见严重错误:
1.未初始化的指针!!!!!!
/*The program is wrong*/
int main(void)
{
 int x;
 int *p;
 x = 10;
 *p = x; /*error, p not initialized*/

 return 0;
}
/*The program have bug*/
int main(void)
{
 int x;
 int *p = NULL;
 x = 10;
 *p = x; /*bug:指针p虽然被初始化为NULL,但是只是一个指向0的指针,只能保证它
不会乱指,然后把x写到未知的地址中去。*/
/*run result:Segmentation fault*/
 return 0;
 
}

2.指针之间的赋值,要加强制转换--好习惯!
除了将指针赋给void *这个通用指针;所以很多返回指针的库函数都用void *这个通用指针来声明返回值;


3.指针可以进行一些二元操作,比较操作,但是前提是二个指针必须指向内存的同一个位置。二指针相减,即它们在内存中的相对位置。

4.下面这个例程描述了一种非常危险的错误 -- 又是未初始化指针!!!
/*This program has a bug.*/
#include <stdio.h>
#include <string.h>

int main(void)
{
 char *p;
 char s[80];
 p = s;
 do{
  gets(s); /*read a string to s[80]*/
 /*Print the decimal equivalent of each character*/
  while(*p){
   printf("%d", *p++);
  } 
 }while(strcmp(s,"done"));
 return 0;
}

/*
***问题是只对p赋值一次,在第二轮循环时,p原来指向的s已经不在,s为新读入的一串新的字符串了,p成了一个未知的危险指针。
*/

/*This program is now correct*/
#include <stdio.h>
#include <string.h>

int main(void)
{
 char *p;
 char s[80];
 do{
  p = s;
  gets(s); /*read a string to s[80]*/
 /*Print the decimal equivalent of each character*/
  while(*p){
   printf("%d", *p++);
  } 
 }while(strcmp(s,"done"));
 return 0;
}

5.还有很多常见的致命的错误都是因为未初始化的指针,或给一个不知道指向哪的指针赋值,惹的祸!
e.g: /*******************************/
 char str_a[20];
 char *str_p;
 gets(str_a);//ok
 gets(str_p);//error
 str_p = malloc(20);
 gets(str_p);//ok
 free(str_p);

/*******************************/
 char str_a[] = "hello world!";
 char *str_p = "hello world!";
 str_a[0] = 'H'; //ok
 *(str_p + 0) = 'H';//error,*str_p是一个常量字符串。
 str_p = str_a;
  *(str_p + 0) = 'H';//ok 

sizeof(str_a) = 13;
sizeof(str_p) = 4;

/************The real routine!***********************************/
#include <stdio.h>
#include <stdlib.h>
int main(){
 char str_a[] = "hello world!";
 char *str_p = "liyang"; //const string,is never chang!
 puts(str_a);
 puts(str_p);
 str_a[0] = 'A';
 str_p = str_a; //"liyang" string never find;
 str_p[0] = 'B';
 *(str_p + 0) = 'C';
 puts(str_a);
 puts(str_p);
 return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值