1.
IRADUKUNDA ISHIMWE Emmanuel
[Link] Kenneth
[Link] Lydia
[Link] olive
[Link] Daniella
[Link] Lucky Clevis
C Programming – Pointers and Dynamic Memory Allocation
Q1. Four Functions Used in Dynamic Memory Allocation
1. malloc()
- Used to allocate a single block of memory.
- Syntax: ptr = (type*) malloc(size);
- It returns NULL if memory is not available.
2. calloc()
- Used to allocate multiple blocks of memory.
- Syntax: ptr = (type*) calloc(number, size);
- It initializes memory with zero.
3. realloc()
- Used to resize previously allocated memory.
- Syntax: ptr = (type*) realloc(ptr, new_size);
4. free()
- Used to release allocated memory.
- Syntax: free(ptr);
Example Program:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
ptr = (int*) malloc(5 * sizeof(int));
if(ptr == NULL) {
printf("Memory not allocated");
return 0;
}
for(int i = 0; i < 5; i++) {
ptr[i] = i + 1;
}
for(int i = 0; i < 5; i++) {
printf("%d ", ptr[i]);
}
free(ptr);
return 0;
}
Q2. Pointer to an Integer
#include <stdio.h>
int main() {
int num = 10;
int *ptr = #
printf("Value of integer: %d\n", num);
printf("Address of integer: %p\n", &num);
printf("Value using pointer: %d\n", *ptr);
return 0;
}
Q3. Swap Two Numbers Using Pointers
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 5, y = 10;
swap(&x, &y);
printf("After swap: x = %d, y = %d", x, y);
return 0;
}
Q4. Sum of Two Numbers Using Pointers
#include <stdio.h>
int main() {
int a = 4, b = 6;
int *p1 = &a, *p2 = &b;
int sum = *p1 + *p2;
printf("Sum = %d", sum);
return 0;
}
Q5. Print Array Elements Using Pointer
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr;
for(int i = 0; i < 5; i++) {
printf("%d ", *(ptr + i));
}
return 0;
}
Q6. Reverse an Array Using Pointers
#include <stdio.h>
void reverse(int *arr, int n) {
int *start = arr;
int *end = arr + n - 1;
int temp;
while(start < end) {
temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
}
int main() {
int arr[5] = {1,2,3,4,5};
reverse(arr, 5);
for(int i=0; i<5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Q7. Dynamically Allocate Memory for an Integer
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int*) malloc(sizeof(int));
if(ptr == NULL) {
printf("Memory not allocated");
return 0;
}
*ptr = 25;
printf("Value = %d", *ptr);
free(ptr);
return 0;
}
Q8. Quadratic Equation Using Pointers
#include <stdio.h>
#include <math.h>
void calculateRoots(float a, float b, float c, float *r1, float *r2) {
float d = b*b - 4*a*c;
if(d > 0) {
*r1 = (-b + sqrt(d)) / (2*a);
*r2 = (-b - sqrt(d)) / (2*a);
} else {
printf("Roots are imaginary");
}
}
int main() {
float a, b, c, r1, r2;
printf("Enter a, b, c: ");
scanf("%f %f %f", &a, &b, &c);
calculateRoots(a, b, c, &r1, &r2);
printf("Root1 = %f\n", r1);
printf("Root2 = %f\n", r2);
return 0;
}