Pointers
Pointers
A pointer is a variable whose value is the address of another variable, i.e., the direct address of the memory location.
Address(&) operator
The address operator denoted by the ampersand character (&), & is a unary operator, which returns the address of a variable.
Indirection(*) operator
Indirection operator denoted by asterisk character (*), * is a unary operator which performs two operations with the pointer.
#include<stdio.h>
int main()
{
int x=25;
int *ptr;
ptr= &x;
printf("Value of x:%d\n", *ptr);
return 0;
}
Output:
Value of x: 25
Pointer expression and Assignment
Pointer expression is used to assign the value of one pointer to another pointer with the help of the assignment(=) operator. The pointer is placed on the right-hand side of an assignment statement to assign its value to another pointer.
#include<stdio.h>
int main(void)
{
int s= 56;
int *ptr1, *ptr2;
ptr1= &s;
ptr2= ptr1;
/* print the value of s twice */
printf("Values of ptr1 and ptr2: %d %d \n", *ptr1, *ptr2);
/* print the address of s twice */
printf("Addresses pointed to by ptr1 and ptr2: %p %p", *ptr1, *ptr2);
return 0;
}
Output:
Values of ptr1 and ptr2: 56 56
Addresses pointed to by ptr1 and ptr2: 0240FF20 0240FF20
Pointer and Function
Call by Value
In a call by value, values of variables are passed to the function from the calling section. This method copies the value of actual parameters into formal parameters.
C program that demonstrates the use of call by value.
#include<stdio.h>
#include<conio.h>
void change(int a);
void main()
{
int a=10;
printf("Before calling function, a=%d", a);
change(a);
printf("After calling function, a=%d", a);
getch();
}
void change(int a)
{
a=a +10;
}
Output:
Before calling function, a=10
After calling function, a= 10
Call by Reference
In a call by reference, the address or location number of the passed parameter is copied and assigned to the local argument of the function, so both the passed parameter and actual argument refer to the same location.
C program that demonstrates the use of call by reference.
#include<stdio.h>
#include<conio.h>
void change(int *a);
void main()
{
int a=10;
printf("Before calling function, a=%d", a);
change(&a);
printf("After calling function, a=%d", a);
getch();
}
void change(int *a)
{
*a=*a + 10;
}
Output:
Before calling function, a=10
After calling function, a= 20