"The complete reference C"
I. Common serious pointer errors:
1. uninitialized pointer !!!!!!
/* 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: although the pointer P is initialized to null, it is only a pointer pointing to 0 and can only be guaranteed.
Then, write X to an unknown address. */
/* Run result: segmentation fault */
Return 0;
}
2. assign values between pointers to enhance the conversion mechanism-good habits!
In addition to assigning pointers to the void * generic pointer, many library functions that return pointers use the void * generic pointer to declare the return value;
3. the pointer can perform some binary operations and comparison operations, but the premise is that the two pointers must point to the same location of the memory. Two pointers subtract, that is, their relative positions in the memory.
4. The following routine describes a very dangerous error-the pointer is not initialized !!!
/* 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;
}
/*
* ** The problem is that P is assigned only once. In the second round of loop, the original s pointed by P is no longer, and S is a new string, P is an unknown dangerous pointer.
*/
/* 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. There are also many common fatal errors caused by Uninitialized pointers or assigning values to a pointer that does not know which to point!
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 is a constant string.
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;
}