Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

resizing an existing array using `realloc`

I defined an array and I tried to resize using realloc() but it is not working. My question is can I do that using arr[] or do I have to use calloc() or malloc() first to define the array and then use realloc()?

this is my working so far…

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

void printArray (int *arr, int size) {

    printf("{");

    for (int i=0; i<size; i++) {
        if (i == size-1) {
            printf("%d", arr[i]);
        } else {
            printf("%d, ", arr[i]);
        }
    }

    printf("}\n");
}


int main () {


    int arr[] = {1, 2, 3};

    int size = sizeof(arr)/sizeof(arr[0]);

    printArray(arr, size);

    ////////////////////////////////////////

    int newSize = size++;

    arr = realloc(arr, newSize*sizeof(int));

    printArray(arr, newSize);


    return 0;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

For starters it seems you mean

int newSize = ++size;

instead of

int newSize = size++;

as Craig Estey pointed in its comment.

This array

int arr[] = {1, 2, 3};

has automatic storage duration.

You may reallocate an array that has allocated storage duration that is an array that was allocated using functions malloc, calloc or realloc.

Pay attention to that if the array arr had allocated storage duration then after the call of realloc

int newSize = ++size; // not size++

arr = realloc(arr, newSize*sizeof(int));

the last element of the array has an indeterminate value because it was not initialized.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading