Search code examples
arrayscelementsizeof

Sizeof operator doesn't work properly after insertion an element


I am trying to make a program in C to insert an element to an array. I used sizeof operator to determine array's total number of elements but after inserting an element and reusing sizeof operator it seems that it doesn't work properly (It gives me the same result without incrementing). Thanks in advance.

// Exercise N9 - Code Win
// Arrays.
#include <stdio.h>

int main()
{
    
    int user_input;
    
    int array[] = {1,2,3,4,5};
    
    
    printf("Hey User !\n");
    printf("Enter an element :\n");
    scanf("%i",&user_input);
    
    int elements_number;
    elements_number = sizeof(array) / sizeof(array[0]);
    
    int new_element_index;
    new_element_index = elements_number;  // Because computer starts from zero.
    
    array[new_element_index] = user_input;
    
    int elements_number_after;
    elements_number_after = sizeof(array) / sizeof(array[0]);
    
    int i;
    
    for (i = 0 ; i < 6 ; i++)
    {
        printf("%i ",array[i]);
    }
    
    printf("\n");
    printf("%i\n",elements_number);
    printf("%i\n",elements_number_after);
    
    return 0;
}


Solution

  • int elements_number;
    elements_number = sizeof(array) / sizeof(array[0]);
    

    The above returns 5 (which should have been stored in a size_t). Continuing onwards:

    int new_element_index;
    new_element_index = elements_number;  // Because computer starts from zero.
        
    array[new_element_index] = user_input;
    

    The last line invokes undefined behavior because the value of new_element_index was 5, and array[5] accesses out of bounds memory. Arrays in C are fixed-size and do not automatically grow. You can't allocate space for 5 integers and then fit 6 into them.

    The second calculation returns 5 because attempting to write to one past the size of the array doesn't actually change the size of the array. It is going to remain 5 no matter what you do.

    What you're looking for is dynamic memory allocation, namely malloc() and realloc().