Search code examples
cmallocrealloc

What am I getting wrong on malloc and realloc understanding?


I was trying to make an array that would resize whilst the program is running. I have come to knowledge of malloc and realloc functions but it seems I'm getting something wrong apparently. Here's the function that I wrote that creates an array based on how many cycles is the loop making.

int* flexibleArray() {
    int *arrayFlex = NULL;
    int number=0, cnt=0;
    while (number!=-1) {
        printf("\nInsert the variable: ");
        scanf("%d", &number);
        if (number==-1){
            break;
        }
        cnt+=1;
        arrayFlex = realloc(arrayFlex, cnt * sizeof(int));
        arrayFlex[cnt-1] = number;
    }
    return arrayFlex;
}

I tried to read the documentation I found on the internet about it, I can't then retrieve the new array after the reallocation.

int *array;
    array = flexibleArray();
    int arraySize = (sizeof(array))/(sizeof(int));
    for(int i=0; i<arraySize; i++) {
        printf("%d ", array[i]);
    }

basically this is where I'm testing the function to see if it does what it should.

I'm new to C, sorry guys. Thanks


Solution

  • Something like this should do it.

    int* flexibleArray() {                                                          
        int *arrayFlex = NULL;                 // needs to be a pointer             
        int number=0, cnt=0;                                                        
        while (number!=-1) {                                                        
            printf("\nInsert the variable: ");                                      
            scanf("%d", &number);                                                   
            if (number==-1){                                                        
                break;                                                              
            }                                                                       
            cnt+=1;                                                                 
            arrayFlex = realloc(arrayFlex, cnt * sizeof(int));                      
            arrayFlex[cnt-1] = number;                                              
        }                                                                           
        return arrayFlex;                                                           
    }     
    

    EDIT: fixed typos.