Home > OS >  C automatically appending null character to a string?
C automatically appending null character to a string?

Time:12-20

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

int main(int argc, const char * argv[]) {
    int i;
    char s1[100] = "Computer Programming Class";
    char s2[100] = "ECE";
    
    int length = (int)strlen(s1);
    for (i = 0; i < length; i  ) {
        s2[i] = s1[length - 1 - i];
    }
    
    s2[i] = '\n';
    printf("%s", s2);
    
    return 0;
}

This was on one of my tests and I don't understand why it works as intended. It's a piece of code that reverses the order of s1 and stores it in s2 and then prints it out. It appears to me that the null character in s2 would be overwritten when s1 is being stored in it backwards, plus the null character in s1 would never be written in s2 since it's starting from the last character. But it prints out just fine. Why?

CodePudding user response:

  1. strlen returns the length of the string in characters not including the null terminator, so i < length does not include the null terminator in its iteration over s1

  2. When you partially initialize an array, as you did with char s2[100] = "ECE"; the remaining elements are already initialized to zero. In other words, your write to s2 as long as length < 99 is guaranteed to be null-terminated.

CodePudding user response:

From the C Standard (6.7.9 Initialization)

21 If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate 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 pointer type, it is initialized to a null pointer;

— 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;

— if it is a union, the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;

Thus in this declaration

char s2[100] = "ECE";

all 96 elements that were not initialized explicitly by elements of the string literal are zero initialized implicitly.

  • Related