Chapter 6
Pointers
A pointer is a variable which stores the address of another variable

P is a pointer
P points to var
The “address of”(&) operator
The address of operator is used to obtain the address of a given variable
If you referred the diagrams above.
&p = 77221111
&Var = 00XBBA77
Format specifier for printing pointer address is %u
The value at address operator (*)
The value at address or * operator is used to obtain the value present at a given memory address it is denoted by *
*(&p) = 77221111
* (&var) = 00XBBA77
How to declare pointer ?
A pointer is declared using the following syntax
int *p; //declare a variable of type int pointer
p = &var;//store address of p in var
Just like pointers of type integer we are so have pointers to char float etc
int *ch_ptr;//pointer to integer
char *ch_ptr;//pointer to character
float *ch_ptr;//pointer to float
Although it’s a good practice to use meaningful variable names we should be very careful while reading and working on program from fellow programmers.
A program to demonstrate pointers
// Show Address of Variable using pointer
#include<stdio.h >
void main()
{
int a=12;
float b=24.25;
char c='a';
printf("\n Address of A : %u",&a);
printf("\n Address of B : %u",&b);
printf("\n Address of C : %u",&c);
}
Output:
Address of A : 65524
Address of B : 65520
Address of C : 65519
Pointer to a pointer
Just like p is pointing to var or storing the address of var we can have another variable k which can further store the address of p so what will be the type of k
int **k;
k = &p;//p is coming from above diagram using in this chapter
We can even go further one level and create a variable e of type int ** to store the address of k we mostly use int* and int** sometimes in real world programs.
Types of function calls
Based on the way we pass arguments to the function function calls are of two types
- Call by value : sending the values of arguments
- Call by reference : sending the address of argument
Call by value
Hair the value of the arguments are passed to the function considere this example
int c = sum (3,4); assume X=3 and y=4
If sum is defined as sum (int a,int b) the values 3 and 4 are copied to a and b now even if we change a and b nothing happens to the variable x and y this is call by value
In C we usually make a call by value
Call by reference
Hear the address of the variables is passed to the function as arguments
Now since the addresses are passed to the function the function can now modify the value of a variable in calling function using * and & operators Example:
void swap(int*x,int*y){int temp;
temp = *x;
*x = *y;
*y = temp;
}
This function is capable of swapping the values passed to it. if a = 3 and b = 4 before a call to swap(a,b) a = 4 and b = 3 after calling swap
int main (){
int a = 3
int b = 4//a is 3 and b is 4
swap(a,b)
return 0; // now a is 4 and b is 3
}