C Pointers with Example
C pointers is special type of variable which holds the address or location of another variable. Pointers point to these locations by keeping a record of the spot at which they were stored. Pointers to variables are found by recording the address at which a variable is stored. It is always possible to find the address of piece of storage in C using the special ‘&’ operator. we can discuss pointers in C,
Lets take this simple example to understand how its performing, For instance: if location were a float type variable, it would be easy to find pointer to it called location_ptr.
float location; float *location_ptr,*address; location_ptr = &(location); or address = &(location);
The declarations of pointers look a little strange at first. The star ‘*’ symbol which stands in front of the variable name is C’s way of declaring that variable to be a pointer.
A pointer is a bundle of information that has two parts. One part is the address of the beginning of the segment of memory that holds whatever is pointed to. The other part is the type of value that the pointer points to the beginning of. This tells the computer how much of the memory after the beginning to read and how to interpret it.
How to declare pointers in C Programming
The first thing to appreciate is that it’s not enough to know that a particular variable, such as pnumber, is a pointer. You and, more importantly, the compiler must know the type of data stored in the variable to which it points. Without this information, it’s virtually impossible to know how much memory is occupied or how to handle the contents of the memory to which it points.
You can declare a pointer to a variable of type int with the following statement:
int *pnumber;
The type of the variable with the name pnumber is int*. It can store the address of any variable of type int.
Note that you can also write the statement like this:
int* pnumber;
This is exactly the same as the previous statement in its effect. You can use either notation, but it is best to stick to one or the other. The statement just creates the pnumber variable but doesn’t initialize it. Uninitialized pointers are particularly hazardous, much more dangerous than an ordinary variable that is uninitialized, so you should always initialize pointer when you declare it.
The idea behind pointers in C is that a high level programmer can now find out the exact location of a variable without ever having to know the actual number involved. Remember: A C pointer is a variable which holds the address of the storage location for another given variable. C provides two operators ‘&’ and ‘*’ which allow pointers to be used in many versatile ways.