0

I need to print values stored in an int array, stopping when a NULL character is encountered ('\0').

So I have this code:

const int display[10] = {1,4,8,2,0,9,2};

int main(){
    int i = 0;

    for (i = 0; i < 10; i++){
        if (display[i] == '\0'){
            break;
        }
        printf("%d\n", display[i]);

    }
    exit(0);
}

I expected to print all the values of display[10] OR break when a '\0' was encountered but my code breaks on display[4] (0) instead of continuing until display[6].

Any advice on how to achieve this, avoiding printing the null characters at the end of my array?

3
  • 3
    integer arrays don't contain NUL characters. Actually, \0 is just 0, so it breaks at the 0 in your array. Commented Oct 24, 2020 at 19:08
  • You could search back from the end of the array for the first non-zero value, but since the array contains a zero, you have no way of knowing if the trailing zeros are data or unused. OTOH you could define const int display[] = {1,4,8,2,0,9,2}; and work out the size. Commented Oct 24, 2020 at 19:12
  • 1
    0 and '\0' are two different ways to write the same thing... same as 42 and 0x2A... or for (;;) { /*...*/ } and while (1) { /*...*/ } Commented Oct 24, 2020 at 19:24

3 Answers 3

2

The null character, '\0', is equal to 0. That's why your loop is only printing the first four elements. It breaks when it encounters 0.

Sign up to request clarification or add additional context in comments.

Comments

2

In C, '\0'==0. If you want to print only the initialized fields, put a sentinel (say, a negative number) right after the last initialized field and break the loop when you either encounter the sentinel or count to 10.

const int display[10] = {1,4,8,2,0,9,2,-1 /* a sentinel */};
for (i = 0; i < 10 && display[i] >= 0; i++) {

Comments

0

You do not need to check whether null is exist or not. First declare the array without total number initialization. Then You can just run the loop by checking the total number of array element. Now the question is how you get the number of element? It is easy.

const int arr[]= { 1, 2, 3};
int size = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < size; i++) {
    printf("%d", arr[i]);
}

2 Comments

Thank you! I'll use a array of arrays, where the number of items in each array will vary (with max number of items being 10). That would work on this case?
You are welcome. Yes it works. You can use vector. It will be more helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.