Home > database >  resizing an existing array using `realloc`
resizing an existing array using `realloc`

Time:07-15

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;
}

CodePudding user response:

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.

  • Related