-1

I want to print an array in c, but only if the specific element of this array is not zero.

Lets assume, foo looks like this 12345678900000000000123 i want only print 123456789123.

int foo[512];
for (i= 0; i < 512; i++) {
    if (foo[i] != '0') {  // This is not working
        printf("%d ", foo[i]);
    }
}
Sudhir Ojha
  • 3,247
  • 3
  • 14
  • 24
johndoe
  • 13
  • 3
  • Try `if (foo[i] > 0)` instead of `if (foo[i] != '0')`. Your `foo` is `int` array not a `char` array. – Sudhir Ojha Jul 23 '20 at 08:20
  • @SudhirOjha oh well, that was an easy one, thanks! – johndoe Jul 23 '20 at 08:23
  • 2
    The problem is you invoke *Undefined Behavior* by accessing elements of the array `foo[]` when the value of those element are *indeterminate*. All bets are off. You must initialize any variable with *automatic storage duration* before attempting to access the value.. `int foo[512] = {0};` will initialize all elements zero. Otherwise, you have to assign a value to each element before attempting to read that value. – David C. Rankin Jul 23 '20 at 09:00

2 Answers2

1

This is because your condition is bad.

if (foo[i] != '0')

whit this, you test whether the foo[i] is equal to a character 0 and not a number 0 for fix this use this condition

if (foo[i] != 0)
1

Your code has two problems.

  1. You didn't initialized the array foo and foo has storage-class auto. The elements contain arbitrary garbage values. Using them in the loop invokes undefined behavior.

  2. '0' is not equal to 0. '\0' is equal to 0. But better use 0 as you only want 0 in its integer nature.

Surrounding integers in apostrophes make them character constants which have specific value. Most likely these values belong to the ASCII character set. '0' for example has the ASCII value 48.

So

if (foo[i] != '0')

is high-probably equivalent to

if (foo[i] != 48)

on your system.


Side Note:

int foo[512];
for (i= 0; i < 512; i++)

You use two times the hardcoded value 512. This technique is susceptible for failures. Better use f.e. a macro constant instead, which ensures that the values are equal:

#define SIZE_ARR 512
...

int foo[SIZE_ARR];
for (i= 0; i < SIZE_ARR; i++)