Saturday, April 2, 2016

Pointers in C


A pointer in c programming is a variable which contains the address of another variable in memory. We can have a pointer to any type of variable. The unary operator “&“gives the ``address of a variable'' where as the dereference operator * gives the ``contents of an object pointed to by a pointer''. In this c programming tutorial we use pointer concept in many programs.

How to use Pointers?


Pointers in c language are very essential for performing certain operations i.e. Gives direct access to variable address. Pointers can be used for that purpose as follows:
First define a pointer variable in c language
Assign the address of a variable to a that pointer variable
Finally Access the value by address available in the pointer variable by using unary operator * that returns the value of the variable located at the address specified by its operand. 
pointers example in c programming
Consider above Diagram :
i  refers to specific memory location in c, suppose it refers to address 65624(random address in system memory) and the Value stored in variable ‘i’ is 5. This address of the variable ‘i’ is stored in another integer variable whose name is ‘j’ and which is refered by address 65522.
Thus we can write as:
i=5;
int *j;
j = &i;
output:
j = 5;
Here j is not ordinary variable , It is special variable and called pointer variable as it stores the address of the another ordinary variable in c programming language.
Following example further clarifies the concept:
Example:
int *array_ptr = array;
printf("Ist element: %i\n", *(array_ptr++));
printf("2nd element: %i\n", *(array_ptr++));
printf("3rd element: %i\n", *array_ptr);
Example Output:
Ist element:100 2nd element: 200 3rd element: 300

0 comments:

Post a Comment