Complementary task for topic: 8

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

Dynamic arrays: Dynamically growing array

Dynamic arrays: Dynamically growing array

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()!
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!!

Solution
#include 


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<3;i++){
        Add_one(&Arr,&size);
    }
    for(int i=0;i<3;i++){
        printf("%f\t",Arr[i]);
    }
    return 0;
}



Explanation

< < previous    next > >