jweinst1
3/26/2017 - 7:55 PM

Uses realloc to extend an int pointer to hold more elements in c

Uses realloc to extend an int pointer to hold more elements in c

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


//example using realloc to extend memory usage in c


int main() {
    int * ptr = malloc(sizeof(int)* 3);
    ptr[0] = 1;
    ptr[1] = 2;
    ptr[2] = 3;
    printf("the first element is:%d\n", ptr[0]);
    printf("the second element is:%d\n", ptr[1]);
    printf("the third element is:%d\n", ptr[2]);
    ptr = realloc(ptr, 4);
    printf("The pointer is reallocated\n");
    ptr[3] = 4;
    printf("[%d,%d,%d,%d] is the new array", ptr[0], ptr[1], ptr[2], ptr[3]);
    
    free(ptr);
    return 0;
}
/*the first element is:1
the second element is:2
the third element is:3
The pointer is reallocated
[1,2,3,4] is the new array*/