Chapter 6 Pointer
Chapter 6 Pointer
A pointer is a variable that stores the address of another VARIABLE
i j
72 | 87994 |
---|
address → 87994 ,87998
j is a pointer
j points to i
The address of “(&) ope1qreator
The address of operator is used to obtain the address of the given variable
If you refer to the diagram above
&i⇒ 87994
&j ⇒87998
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 *
*(&i) =72
*(&j) =87994
How to declare a Pointer ?
A pointer is declared using the following syntax
int *j; ⇒ declare a variable j of typr int-pointer
j=&i ⇒ Store address of in j
Just like a pointer of type integer, We also have pointer to char, float etc.
int* ch-ptr; → Pointer to integer
char* ch-ptr; -. Pointer to character
float* ch-ptr; → Pointer to float
Although its a good active to use meaningful variable names, we should be very careful while reading 7working on programs from fellow programmers.
A program to demonstrate pointers
#include<stdio.h>
int main(){
int i=8;
int*j;
j=&i;
printf(”Add i =%u\\n”,&i)
printf(”Add i =%u\\n”,&j)
printf(”Add j =%u\\n”,&j)
printf(”Add i =%d\\n”,&i)
printf(”Add i =%d\\n”,*(&i))
printf(”Add i =%d\\n”,&j)
return0;
}
Output:
Add i=87994
Add i=87994
Add j=87994
value i=8
value i=8
value i=8
This program sums it all. If you understand it, you have got the ides of pointers
Pointer to pointer
Just like j is pointing to i or storing the address of i, we can have another variable which can further store the address of j. what will be the type of K.
int**k;
k=&j;
We can even go further one level and create a variable L 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 arguments
Call by value
Here the value of the arguments are passed to the function . Consider this example
int c =sum(3,4); = assume x=3 and y=4
If sum is defined as sum , the values of 3 and 4 are copied to a and b . now even if we change a and b, nothing happens to this variables x and y.
This is call by value.
In c we usually make a call by value
Call by reference
Here the address of the variable is passed to the function as arguments.
Now since the addresses are passed to 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;
xxx = *y;
*y = temp;
}
This function is capable of swapping the values passed to it if a=3 and b=3 after calling swap.
int main(){
int a =3
int b=4 ⇒ a is 3 and b is 4
swap (a,b)
swap(a,b)
return 0; ⇒ now a is 4 and b is 3
}
Comments
Post a Comment