Dynamic Memory Allocation(DMA) Practice Question in C

Dynamic Memory Allocation(DMA) Questions:

Q: WAP to allocate memory of size n, where n is entered by the user?
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *ptr, n;
    printf("Enter number: ");
    scanf("%d", &n);

    ptr = (int *) malloc(n * sizeof(int));

    for(int i=0; i<n; i++){
        printf("%d\n", ptr[i]);
    }

    return 0;
}

Q: Allocate memory for 5 numbers. Then dynamically increase it to 8 numbers.

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *ptr;
    ptr = (int *) malloc(5 * sizeof(int));

    ptr[0] = 1;
    ptr[1] = 2;
    ptr[2] = 3;

    ptr = realloc(ptr, 8);

    for (int i=0; i<8; i++) {
        printf("%d\n", ptr[i]);
    }

    free(ptr);

    return 0;
}

Q: Allocate memory to store first 5 odd numbers, then reallocate it to store forest 6 even number.

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *ptr;
    ptr = (int *) malloc(5 * sizeof(int));

    ptr[0] = 1;
    ptr[1] = 3;
    ptr[2] = 5;
    ptr[3] = 7;
    ptr[4] = 9;

    for (int i=0; i<5; i++) {
        printf("%d\n", ptr[i]);
    }

    ptr = realloc(ptr, 6);

    ptr[0] = 2;
    ptr[1] = 4;
    ptr[2] = 6;
    ptr[3] = 8;
    ptr[4] = 10;
    ptr[5] = 12;

    for (int i=0; i<6; i++) {
        printf("%d\n", ptr[i]);
    }

    free(ptr);

    return 0;
}
Q: Write a program to calculate perimeter of rectangle. Take sides a and b from the user.
#include <stdio.h>
#include <stdlib.h>

int main() {
    float *ptr, a, b;
    ptr = (float *) calloc(2, sizeof(float));
    printf("Enter two numbers\n");
    scanf("%f %f", &a, &b);
    printf("Perimeter of rectange is %f", 2*(a+b));
    free(ptr);
    return 0;
}
Q: Take a number n from user and output is cube.
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *ptr, n;
    ptr = (int *) calloc(1, sizeof(int));
    printf("Enter a number : ");
    scanf("%d", &n);
    printf("Cube of %d is %d", n, n*n*n);
    free(ptr);
    return 0;
}
Q: Create an array of multiplication table of 7 upto 10 (7 x 10 = 70). Use realloc to make it store 15 number (from 7 x 1 to 7 x 15).
#include <stdio.h>

int main() {
    
    return 0;
}



Post a Comment

0 Comments