Complementary task for topic: 8

M Nemeth · 2023-08-29 15:21:04.628218'

Dynamic arrays: Dynamically delete an element

Dynamic arrays: Dynamically delete an element

Crate a C program, that can read as many real number from the user as it is needed. Add a new element should be in a separate function. Do not use realloc()! Create a function that can delete an element passed by value (first element is OK), use it!
print the result!

Hint: When you add new element, you need to make the array one bigger. For that you need to allocate, copy, add the new element. The old pointer must be earesed as soon as possible!!
Delete an element rewured to search for it, get the index, allocate one less array if found such an element, and copy the remaining elements

Solution
#include 

int delete_one(double** Arr,int* size,double to_delete){ //return value 0 not found, else found
    int index=-1; //make it invalid
    for(int i=0;i<*size;i++){
        if((*Arr)[i]==to_delete){
            index=i;
            break; //to find the first, not the last
        }
    }
    if(index==-1)
        return 0;
    //we do not need else, as the return terminates the function
    double* Arr2=(double*)malloc((*size-1)*sizeof(double)); //space for the new array
    for(int i=0,j=0; i<*size; i++,j++){//we need two indexes to skip the missing one's place
            if(i==index){
                j--;
                continue; //using i++ leads out of the range if the found is the last
            }
        Arr2[j]=(*Arr)[i];
    }
    free(*Arr);

    *Arr=Arr2;
    (*size)--;//Careful! ++ has higher precendence than *!

    return 1;

    }






void Add_one(double** Arr,int* size){
    double new_elem;
    printf("give a new element:\n");
    scanf("%lf",&new_elem);

    double* Arr2=(double*)malloc((*size+1)*sizeof(double));

    for(int i=0; i<*size; i++){
        Arr2[i]=(*Arr)[i];
    }
    free(*Arr);
    Arr2[*size]=new_elem;

    *Arr=Arr2;
    (*size)++;//Careful! ++ has higher precendence than *!

    return;


}

int main()
{
    int size=0;
    double* Arr=NULL;
    for(int i=0;i<5;i++){
        Add_one(&Arr,&size);
    }
    double to_delete;
    printf("What to delete?\n");
    scanf("%lf",&to_delete);
    delete_one(&Arr,&size,to_delete);
    for(int i=0;i
Explanation

< < previous    next > >