C - Why is a string terminator automatically being added when assigning individual chars to the array?

270 views Asked by At

Although my array is only of size 3, and I've assigned a char to each element, a NULL Terminator is still automatically added. What is causing a NULL Terminator to be added in my code?

int main(void)
{
    char s[3];
    s[0] = 'f';
    s[1] = 'o';
    s[2] = 'o';

    int i = 0;

    while (s[i] != '\0')
        printf("%c", s[i++]);

    printf("\n");

    if (s[i] == '\0')
        printf("Null Terminator Added\n");
}   
1

There are 1 answers

0
Nate Eldredge On BEST ANSWER

It's not "automatically added". When you try to access s[3], you are accessing memory that's not part of the array s. On your machine, it appears that this memory happens to contain a null byte. You can't rely on that happening; maybe on another machine, or another run, that memory will happen to contain something else. Or maybe the computer will detect an illegal memory access and your program will crash. Or maybe your program will break in some other subtle and unexpected way.

Short answer: your program is buggy, and you can't really draw any meaningful conclusions from its behavior.