written 5.7 years ago by | • modified 5.7 years ago |
Subject : Structured Programming Approach
Title : Pointers and Files
Difficulty : Medium
written 5.7 years ago by | • modified 5.7 years ago |
Subject : Structured Programming Approach
Title : Pointers and Files
Difficulty : Medium
written 5.7 years ago by | • modified 5.7 years ago |
Pointer: A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address. The general form of a pointer variable declaration is −type *var-name;
Uses of pointer:
1.Pointers reduce the length and complexity of a program.
2.They increase execution speed.
3.A pointer enables us to access a variable that is defined outside the function.
4.Pointers are more efficient in handling the data tables.
5.The use of a pointer array of character strings results in saving of data storage space in memory.
Array of Pointers: Just like we can declare an array of int, float or char etc, we can also declare an array of pointers, here is the syntax to do the same.
Syntax:
datatype *array_name[size];
Example:
int *arrop[5];
Here arrop is an array of 5 integer pointers. It means that this array can hold the address of 5 integer variables, or in other words, you can assign 5 pointer variables of type pointer to int to the elements of this array. arrop[i] gives the address of i th element of the array. So arrop[0] returns address of variable at position 0, arrop[1] returns address of variable at position 1 and so on.To get the value at address use indirection operator (*).So *arrop[0] gives value at address[0], Similarly *arrop[1] gives the value at address arrop[1] and so on.
Program:
#include <stdio.h>
#include <conio.h>
void swap( int *x, int *y )
{
int t ;
t = *x ;
*x = *y ;
*y = t ;
printf(“In function :”);
printf( "\nx = %d \t y = %d\n", *x,*y);
}
void main( )
{
int a,b;
printf(“Enter the value of a : ”);
scanf(“%d”, &a);
printf(“Enter the value of b : ”);
scanf(“%d”, &b);
printf(“Before swapping : \n”);
printf ( "\na = %d \t b = %d\n", a, b ) ;
swap ( &a, &b ) ;
printf(“After swapping : \n”);
printf ( "\na = %d \t b = %d\n", a, b ) ;
getch();
}
Output:
Enter the value of a : 10
Enter the value of b : 20
Before swapping :a=10 b=20
In function :
x=20 y=10
After swapping :
a=20 b=10