“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;
}