StudyLover
  • Home
  • Study Zone
  • Profiles
  • Typing Tutor
  • Contact us
  • Sign in
StudyLover Program #38 (U4): realloc — Grow/Shrink a Dynamic Array
Download
  1. C Programming
  2. C Programming Practice
Program #37 (U4): malloc — Dynamic Array and Mean : Program #39 (U4): struct Student {roll, name, marks} with Pass/Fail
C Programming Practice

Task: Start with a small dynamic array, then add/remove elements by resizing with realloc. Keep data consistent and free at the end.

 
#include <stdio.h>

#include <stdlib.h>

 
int main(void){

    int n, m, r, *a;

 
    printf("Initial size n: ");

    if(scanf("%d", &n)!=1 || n<0){ printf("Invalid n.\n"); return 0; }

 
    a = (int*)malloc(sizeof(int) * (n>0?n:1));

    if(!a){ printf("Allocation failed.\n"); return 0; }

 
    printf("Enter %d integers: ", n);

    for(int i=0;i<n;++i) scanf("%d", &a[i]);

 
    printf("Grow by m elements: ");

    if(scanf("%d", &m)!=1 || m<0){ printf("Invalid m.\n"); free(a); return 0; }

    a = (int*)realloc(a, sizeof(int)*(n+m));

    if(!a){ printf("Realloc failed.\n"); return 0; }

 
    printf("Enter %d more integers: ", m);

    for(int i=0;i<m;++i) scanf("%d", &a[n+i]);

    n += m;

 
    printf("Shrink by r elements (<=current size): ");

    if(scanf("%d", &r)!=1 || r<0 || r>n){ printf("Invalid r.\n"); free(a); return 0; }

    n -= r;

    a = (int*)realloc(a, sizeof(int)* (n>0?n:1));

    if(!a){ printf("Realloc failed after shrink.\n"); return 0; }

 
    printf("Array now (%d elems): ", n);

    for(int i=0;i<n;++i) printf("%d ", a[i]);

    printf("\n");

 
    free(a);

    return 0;

}

 

 

Program #37 (U4): malloc — Dynamic Array and Mean Program #39 (U4): struct Student {roll, name, marks} with Pass/Fail
Our Products & Services
  • Home
Connect with us
  • Contact us
  • +91 82955 87844
  • Rk6yadav@gmail.com

StudyLover - About us

The Best knowledge for Best people.

Copyright © StudyLover
Powered by Odoo - Create a free website