DSA LAB 1 Program
Program for using Dynamic Function (malloc(), calloc(), realloc(), free(0) function
// malloc() & free() function
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int *)malloc(n * sizeof(int));
// if memory cannot be allocated
if (ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
for (i = 0; i < n; ++i)
{
printf("Enter %d elements : ",i+1);
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
// deallocating the memory
free(ptr);
return 0;
}
// Output
Enter number of elements: 5
Enter 1 elements : 5
Enter 2 elements : 8
Enter 3 elements : 6
Enter 4 elements : 3
Enter 5 elements : 5
Sum = 27
// calloc() & free() function
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int *)calloc(n, sizeof(int));
// if memory cannot be allocated
if (ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
for (i = 0; i < n; ++i)
{
printf("Enter %d elements : ",i+1);
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
// deallocating the memory
free(ptr);
return 0;
}
// output
Enter number of elements: 5
Enter 1 elements : 4
Enter 2 elements : 74
Enter 3 elements : 7
Enter 4 elements : 64
Enter 5 elements : 4
Sum = 153
// malloc(), realloc & free() function
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, i, n1, n2;
printf("Enter size: ");
scanf("%d", &n1);
ptr = (int *)malloc(n1 * sizeof(int));
printf("Addresses of previously allocated memory:\n");
for (i = 0; i < n1; ++i)
printf("%pc\n", ptr + i);
printf("\nEnter the new size: ");
scanf("%d", &n2);
// rellocating the memory
ptr = realloc(ptr, n2 * sizeof(int));
printf("Addresses of newly allocated memory:\n");
for (i = 0; i < n2; ++i)
printf("%pc\n", ptr + i);
free(ptr);
return 0;
}
// output
Enter size: 5
Addresses of previously allocated memory:
00B51AB0c
00B51AB4c
00B51AB8c
00B51ABCc
00B51AC0c
Enter the new size: 4
Addresses of newly allocated memory:
00B51AB0c
00B51AB4c
00B51AB8c
00B51ABCc
Comments
Post a Comment