Remove zero entries from an array in C

Viewed 10246

I have an array of values x = {0,0,1,2,3,0,0,7,8} and I want to remove the zero entries using C.

Attempt:

I am attempting to loop through each value in the array and check if the entry is not equal to zero. If this condition is true, then I am attempting to populate a new array with original array value.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    int x[] = { 0, 0, 1, 2, 3, 0, 0, 7, 8 };
    int i;
    int x_upd[100];
    for (i = 0; i < 9; i++) {
        if (x[i] != 0) {
            x_upd[i] = x[i]; // if true, populate new array with value
        }
    }
    for (i = 0; i < 9; i++) {
        printf(" Peak updated %d\t", x_upd[i]); //
    }
    return 0;
}

The output is not giving me the values {1,2,3,7,8} as desired. Instead, I am getting garbage values at the location where the zeros used to be.

Any advice on what I am doing wrong here? Do I need an else statement?

11 Answers
Related