Pointer Operators * and &

& is a unary operator that returns the address of its operand which must be a variable.

For Example

int *m ;
int count=125, i ;/* m is a pointer to int, count, i are integers */
m = &count ;

The address of the variable count is placed in the pointer variable m.

The * operator is the complement of the address operator & and is normally termed the indirection operator. Like the & operator it is a unary operator and it returns the value of the variable located at the address its operand stores.
For Example
i = *m ;

assigns the value which is located at the memory location whose address is stored in m, to the integer i. So essentially in this case we have assigned the value of the variable count to the variable i.

One of the most frequent causes of error when dealing with pointers is using an uninitialised pointer. Pointers should be initialised when they are declared or in an assignment statement. Like any variable if you do not specifically assign a value to a pointer variable it may contain any value. This is extremely dangerous when dealing with pointers because the pointer may point to any arbitrary location in memory, possibly to an unused location but also possibly to a memory location that is used by the operating system. If your program tries to change the value at this address it may cause the whole system to crash. Therefore it is important to initialise all pointers before use either explicitly in your program or when defining the pointer.

A pointer may also be initialised to 0 ( zero ) or NULL which means it is pointing at nothing. This will cause a run-time e ror if the pointer is inadvertently used in this state. It is useful to be able to test if a pointer has a null value or not as a means of determining if it is pointing at something useful in a program.

Pointer Operators * and & Pointer Operators * and & Reviewed by Unknown on 04:43 Rating: 5

No comments:

Powered by Blogger.