Previous | Home | Next |
# Pointer
In c a pointer is a variable that points to or references a memory location in which data is stored. Each memory cell in the computer has an address that can be used to access that location so a pointer variable points to a memory location we can access and change the contents of this memory location via the pointer.
Pointer is a address variable that hold the address of another variable. We can have a pointer to any variable type. The & is a unary operator that gives the address of a variable. The * (indirection or dereference operator), that gives the contents of an object that pointed to by a pointer.
(&) Ampersand operator
//Using & operator show the address of variable void main( ) { int a = 5 ; printf ( "\nAddress of a = %u", &a ); printf ( "\nValue of a = %d", a ); }
Address of a=1444
Value of a=5
Note: In above example variable a memory address is 1444. Means using this & we find the memory address.
Syntax
data_type_name *variable_name int *ptr; //Declare a pointer
# Now using pointer, once we declare a pointer variable we must point it to something we can do this by assigning to the pointer the address of the variable like:
To access memory address of variable x you have to use pointer. To declare pointer you use asterisk notation (*) after pointer's data type and before pointer name as follows:
int x = 10; /* Now pointer ptr to points to memory address of variable x */ const int *ptr; /* you can use address-of operator (&) */ ptr = &x; /* Show address of variable x */ printf("Address of x is %d\n", ptr); /* Variable x */ printf("Value of x is %d\n", *ptr); /* you can change the content of variable x using poiter variable */ *ptr += 10;// Increasing the value printf("Value of x after increasing %d\n",x); *ptr -= 5;// Decreasing the value printf("Value of x after decreasing %d\n",x);
Address of x is 1310580
Value of x is 10
Value of x after increasing 20
Value of x after decreasing 15
Previous | Home | Next |