简体   繁体   中英

Confusion regarding output of a program related to Null character

In the below program arr is a char array whose length is 4. On running it in C compiler I found that the output is tjyh.

#include <stdio.h>

int main() {
    char arr[4];
    arr[0]='t';
    arr[1]='j';
    arr[2]='y';
    arr[3]='h';
    printf("%s",arr);
    return 0;
}

I am confused as where is the Null character. Since a string ends with a '\\0' there should be space to accommodate it. How does "%s" know when to stop. Since there is no '\\0', there should be garbage values after tjyh or the output should just be tjy since the last character is '\\0' which replaced 'h'.

Edit: Well, I ran this code in Codechef compiler and got the output to be tjyh and no garbage values and if you think that it should also print garbage values then please tell me for how long should it print garbage values as I did not entered '\\0', so when would the program stop printing?

Since there is no '\\0', there should be garbage values after tjyh…

How do you know there is no '\\0' there? You put letters in arr[0] , arr[1] , arr[2] , and arr[3] . What did you put after that? Nothing. So how do you know what is there?

In fact, you defined an array of only four bytes, char arr[4]; , so the compiler arranged that much space for you. You do not know what is in memory beyond that array. You do not know whether there is a null character there or not.

So, maybe there is a null character there, and, when you execute printf("%s",arr); , it prints the four characters you assigned, sees the null character, and stops.

In other circumstances, maybe in a more complicated program, there might be other data after the array arr , and printf would not see a null character just after arr and would not stop.

The above is what happens in a simple C implementation. However, compilers are getting more sophisticated, and a compiler might recognize that the call to printf with an unterminated string results in behavior that is not defined by the C standard. During optimization, code that has undefined behavior may be transformed in unexpected ways, so your program might not print “tjyh” at all; it might trap or execute completely different code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM