Search code examples
coptimizationmallocdynamic-arraysrealloc

Is this truly best way to delete last element in C?


I have a code where I need to delete last element of array. I made this code but I am wondering is there a more optimised way of doing this?

My version:

void DeleteLast(int** array, int* size)
{
    int newsize=(*size)-1;
    int* temparr = (int*)malloc(newsize*sizeof(int));
    for (int i = 0; i<newsize; i++) temparr[i]=(*array)[i];
    *array = (int*)malloc(newsize*sizeof(int));
    for (int i = 0; i<newsize; i++) (*array)[i]=temparr[i];
    *size=newsize;
    free(temparr);
}

It just looks like execive work so I am wondering if there is a way to optimize it if needed.


Solution

  • You could have copied the value of temparr into *array instead of making an additional allocation:

    void DeleteLast(int** array, int* size)
    {
        int newsize=(*size)-1;
        int* temparr = malloc(newsize*sizeof(int));
        for (int i = 0; i<newsize; i++) temparr[i]=(*array)[i];
        free(*array);
        *array = temparr;
        *size=newsize;
    }
    

    Or even better, just use realloc:

    void DeleteLast(int** array, int* size)
    {
        int newsize=(*size)-1;
        *array = realloc(*array,newsize*sizeof(int));
        *size=newsize;
    }