The pointer is the C language only so successful one of the important reasons, of course, anything, is often a two-sided, essentially one, looks is both sides, the key is to ingenious, not more than the distinction between advantages, disadvantages.
C language is mainly for the hardware and system of the underlying programming, in the hardware and system-level programming, the flexibility of the data requirements, in other words, the meaning of the data needs to change constantly, and the data type determines the meaning of the data, pointers an important role is to achieve the conversion of data types, For example, to represent the machine code as a 0X3F8CCCCD floating-point number:
1 2 3 4 5 6 7 8 9 10 |
#include <stdio.h> int main () {unsigned UI = 0X3F8CCCCD; Float F1 = (float) UI; Error, the meaning of the conversion is not correct printf ("%f\n", F1); float F2 = * (float *) (&UI); Correct, change the meaning of memory data by pointer printf ("%f\n", F2); return 0; } |
Pointers are useful for changing the data context environment, such as detecting the sequence of storage supported by the CPU.
1 2 3 4 5 6 7 8 9 10 11 |
#include <stdio.h> char endian (void) {unsigned UI = ~0-1 return (* (unsigned char *) (&UI) = 0xFE)? ' L ': ' B '); int main () {endian () = = ' L '? printf ("Little Endian cpu\n"): printf ("Big endian cpu\n"); return 0; } |
If C language does not have a pointer, of course, can come up with other methods, but far from the convenience of pointers.
The disadvantage of pointers, perhaps for beginners, often not easy to understand, and the use of pointer programming often appear some inexplicable errors, and in peacetime use the C language for application development, as if pointers are really not useful, these are not the problem, the key is to see the use of C language, what to do development, on what project.