Search code examples
carraysdynamic-memory-allocation

How to insert an element at the last position in an array dynamically in C?


I'm a newbie in C and trying to insert a number at the last position in C such that, the size of the array is changed over time.

The first array is like this:

temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};

Now how can we insert those values in temp that are != 0 to a new array which has a defined length of 5: tmp

Here's what I'm trying:

void push(int arr[], int value, int current){
  arr[current] = value;
}

int main(void) { 

  int temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
  int tmp[5];

  for(int i=0;;i++){
    if(temp[i]) push(tmp, temp[i],sizeof(tmp)/sizeof(tmp[0]));
    // I don't put i < 10 int the loop initialization. Since the tmp's length is just 5

  }
  // I put sizeof(tmp)/sizeof(tmp[0]) there because we want at every time the tmp is inserted a new value,
  // it's length will change (increase by 1). 
  // So next loop round, the new value will be added to the last position
  // But I failed to do so

} 

Current output:

exited segmentation fault
// I'd be very grateful if someone can also explain for me why this error happens

Desired output:

tmp[5] = {1, 2, 5, 6, 8}

Solution

  • C does not have dynamic arrays. Arrays have a fixed size determined from their definition. You can allocate objects with malloc() that behave as arrays, but you must keep track of their allocated size separately. Appending an element requires reallocating the array so its address in memory may change.

    In your code, tmp has a fixed size of 5 elements. You could maintain an index specifying how many elements are used and update that in the push function:

    #include <stdio.h>
    
    int push(int arr[], int value, size_t size, size_t *current) {
        if (*current < size) {
            arr[(*current)++] = value;
            return 0;
        } else {
            /* array is full */
            return -1;
        }
    }
    
    int main(void) { 
        int temp[10] = { 1, 2, 0, 0, 5, 6, 0, 8, 0, 0 };
        int tmp[5];
        size_t pos = 0;
    
        for (size_t i = 0; i < sizeof(temp) / sizeof(temp[0]); i++) {
            if (temp[i])
                push(tmp, temp[i], sizeof(tmp) / sizeof(tmp[0]), &pos);
        }
    
        printf("tmp:");
        for (size_t i = 0; i < pos; i++) {
            printf(" %d", tmp[i]);
        }
        printf("\n");
        return 0;
    }