FYBCA Sem 2 C Lang Unit 2 - Pointer
FYBCA Sem 2 C Lang Unit 2 - Pointer
Pointers store addresses of the memory locations, this what everyone knows, let me
explain why sometimes it's better to use pointers instead of original variables:
• They save space: space is very precious & saving space leads to gaining
time thus better performance. Suppose you're working with very large data
types or you have yourself have created a very large object. Now if you want
to pass this object to a function, then the compiler will create a copy of this
object in the memory, then this copy will be passed to the function & then
the processing on the value will begin. In this way you're not using the
memory efficiently cos you have to create a copy of such a large object
without any good reasons. But if you pass the address of this variable to the
target function then the processing will be done directly on the original
object & hence no time or memory will be wasted on the duplication of the
original object. Thus speed & space efficiency is gained.
• They can increase speed during iterative traversal: for example if you
wish to traverse the array then you'll just write a for loop to iterate the index
value, but in actual you are incrementing the memory address. So if you're
doing performance conscious back-end coding then instead of first
incrementing the index & then updating the memory address you can
directly access the next memory location & hence performance improvement.
• Changes made are observed everywhere: suppose you have a program
with independent threads. Now instead of creating copy of the same data for
each one of them, you provide them with the address of the original value &
thus if any change is made to the value then every thread will get the latest
updates.
• Reading variables not in the same scope: I just read on Yahoo_answers
that using pointers you can access variables which were not declared in the
same scope.
& Ofcourse all time favourite Dynamic Memory Allocation is possible due to
pointers.
Example:
// C program to illustrate Pointers
#include <stdio.h>
void Pointer1()
{
#include<stdio.h>
int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
int *ptr = arr;
printf("%p\n", ptr);
return 0;
}
Program2
int myNumbers[4] = {25, 50, 75, 100};
int *ptr = myNumbers;
int i;
Result:
25
50
75
100
int main()
{
// declaring some temp variables
int var1 = 10;
int var2 = 20;
int var3 = 30;
// array of pointers to integers
int* ptr_arr[3] = { &var1, &var2, &var3 };
// traversing using loop
for (int i = 0; i < 3; i++) {
printf("Value of var%d: %d\tAddress: %p\n", i + 1, *ptr_arr[i], ptr_arr[i]);
}
return 0;
}
Output
Value of var1: 10 Address: 0x7fff1ac82484
Value of var2: 20 Address: 0x7fff1ac82488
Value of var3: 30 Address: 0x7fff1ac8248c
Explanation:
Program
#include <stdio.h>
void swap(int *n1, int *n2);
void main()
{
int num1 = 5, num2 = 10;
// address of num1 and num2 is passed
swap( &num1, &num2);
printf("num1 = %d\n", num1);
printf("num2 = %d", num2);
getch();
}
void swap(int* n1, int* n2)
{
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
Output :
num1 = 10
num2 = 5
#include <stdio.h>
struct person
{
int age;
float weight;
};
int main()
{
struct person *personPtr, person1;
personPtr = &person1;
printf("Displaying:\n");
printf("Age: %d\n", personPtr->age);
printf("weight: %f", personPtr->weight);
return 0;
}
Run Code
In this example, the address of person1 is stored in the personPtr pointer using
personPtr = &person1;.
Now, you can access the members of person1 using the personPtr pointer.
By the way,
Pointers to Pointer:
As we know that, a pointer is used to store the address of a variable in C.
Pointer reduces the access time of a variable. However, In C, we can also define a
pointer to store the address of another pointer. Such pointer is known as a double
pointer (pointer to pointer). The first pointer is used to store the address of a variable
whereas the second pointer is used to store the address of the first pointer. Let's
understand it by the diagram given below.
Since C is a structured language, it has some fixed rules for programming. One of
them includes changing the size of an array. An array is a collection of items stored
at contiguous memory locations.
As can be seen, the length (size) of the array above is 9. But what if there is a
requirement to change this length (size)? For example,
• If there is a situation where only 5 elements are needed to be entered in this
array. In this case, the remaining 4 indices are just wasting memory in this
array. So there is a requirement to lessen the length (size) of the array from 9 to
5.
• Take another situation. In this, there is an array of 9 elements with all 9 indices
filled. But there is a need to enter 3 more elements in this array. In this case, 3
indices more are required. So the length (size) of the array needs to be changed
from 9 to 12.
This procedure is referred to as Dynamic Memory Allocation in C.
Therefore, C Dynamic Memory Allocation can be defined as a procedure in which
the size of a data structure (like Array) is changed during the runtime.
C provides some functions to achieve these tasks. There are 4 library functions
provided by C defined under <stdlib.h> header file to facilitate dynamic memory
allocation in C programming. They are:
1. malloc()
2. calloc()
Before learning above functions, let's understand the difference between static
memory allocation and dynamic memory allocation.
Now let's have a quick look at the methods used for dynamic memory allocation.
#include<stdio.h>
#include<stdlib.h>
int main(){
intn,i,*ptr,sum=0;
C calloc() method:
“calloc” or “contiguous allocation” method in C is used to dynamically allocate
the specified number of blocks of memory of the specified type. it is very much
similar to malloc() but has two different points and these are:
It initializes each block with a default value ‘0’.
It has two parameters or arguments as compare to malloc().
Syntax of calloc() in C
ptr = (cast-type*)calloc(n, element-size);
here, n is the no. of elements and element-size is the size of each element.
For Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25 elements each with the
size of the float.
#include<stdio.h>
#include<stdlib.h>
int main(){
intn,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
Output
realloc() function in C
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc()
function. In short, it changes the memory size.
ptr=realloc(ptr, new-size)
C free() method
“free” method in C is used to dynamically de-allocate the memory. The memory
allocated using functions malloc() and calloc() is not de-allocated on their own.
Hence the free() method is used, whenever the dynamic memory allocation takes
place. It helps to reduce wastage of memory by freeing it.
Syntax of free() in C
free(ptr);
#include <stdio.h>
#include <stdlib.h>
void main() {
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
getch();
Output
Enter number of elements: 3
Enter elements: 100
20
36
Sum = 156
Here, we have dynamically allocated the memory for n number of int.
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
void main() {
int *ptr, i , n1, n2;
printf("Enter size: ");
scanf("%d", &n1);
Enter size: 2
Addresses of previously allocated memory:
26855472
26855476