if I initialize a char array to zero/{0} do I have to null terminate?

3.4k views Asked by At

Say for instance I declare a char array with all values set to zero in the following fashion:

char array[4] = {0};

If I assign it values, for instance:

array[0] = 'A';
array[1] = 'B';
array[2] = 'C';

Do I need to null terminate the array like so?:

array[3] = '\0';

or does the operation char array[4] = {0} null terminate previous to any assignment?

2

There are 2 answers

7
Lundin On BEST ANSWER

Do I need to null terminate the array like so?

No. '\0' is just a fancy way of writing 0. It's a way to write self-documenting code referring to the null terminator specifically, out of tradition. (It's actually just a zero written as an octal escape sequence, of all things.)

Since you already set all items to 0, there is no need for an extra \0.

0
Vlad from Moscow On

This declaration

char array[4] = {0};

is equivalent to

char array[4] = { 0, 0, 0, 0 };

From the C Standard (6.7.9 Initialization)

19 The initialization shall occur in initializer list order, each initializer provided for a particular subobject overriding any previously listed initializer for the same subobject;151) all subobjects that are not initialized explicitly shall be initialized implicitly the same as objects that have static storage duration.

and

10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:

— if it has arithmetic type, it is initialized to (positive or unsigned) zero; — if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits; ...

So the element array[3] contains 0. Until it will be overwritten the array contains a string.

An alternative initialization by zeroes of a character array is the following

char array[4] = "";

or the following

char array[4] = { "" };

or even the following

char array[] = { [3] = '\0' };

Here is a demonstrative program.

#include <stdio.h>

int main(void) 
{
    char array[] = { [3] = '\0' };
    
    array[0] = 'A';     //  the array contains a string
    
    printf( "%s\n", array );
    
    array[1] = 'B';     //  the array contains a string
    
    printf( "%s\n", array );
    
    array[2] = 'C';     //  the array contains a string
    
    printf( "%s\n", array );
    
    array[3] = 'D';     //  the array does not contain a string
    
    printf( "%.*s\n", ( int )sizeof( array ), array );
    
    
    return 0;
}

The program output is

A
AB
ABC
ABCD