0

When I was compiling below code it shows "helloworld" rather than "hello". Why is this happening?

#include<stdio.h>

int main() {
    
    char s1[6] = {'h', 'e', 'l', 'l', 'o'};
    char s2[10] = {'w','o','r','l','d'}; 
    printf("%s\n", s1);
   
    return 0;
}
Nakib
  • 19
  • 4
  • 1
    `s1` is not a string. `s2` is a string by accident. Please study null termination, see the linked duplicate and the beginner FAQ here: [Common string handling pitfalls in C programming](https://software.codidact.com/posts/284849) – Lundin Mar 24 '22 at 09:22
  • If i declare char s1[] = {'h', 'e', 'l', 'l', 'o'}; then there is a space for null termination. Why does it also show "helloworld" ?@Lundin – Nakib Mar 24 '22 at 09:29
  • 1
    @Lundin true except that the remaining bytes of `s2` are set to `0` by design, not by accident. – Weather Vane Mar 24 '22 at 09:29
  • 1
    @Nakib No there isn't. You need to study arrays (and pointers) before studying strings. – Lundin Mar 24 '22 at 09:30
  • @WeatherVane No, it's by accident. A seasoned application programmer would have written `... 'd', '\0'};` _self-documenting code_ and not silently let the rest get initialized as if they have storage duration. When we can't tell if some code is relying on implicit language features by design or by accident, then that code is bad and needs to either be rewritten or have comments appended. – Lundin Mar 24 '22 at 09:33
  • 1
    Why does your code show _"helloworld"_: apparently _your_ compiler has arranged the variabls `s1` and `s2` in memory in a way that the first byte of `s2` is immediately after the last byte of `s1`, which is not surprising. What `printf("%s\n", s1)` does here is displaying sucessive characters of `s1` until a 0 is encountered. Another compiler might arrange the variables differently and output would be different. – Jabberwocky Mar 24 '22 at 09:34
  • 1
    @Lundin I get your point: "design" of the language, not of the programmer. – Weather Vane Mar 24 '22 at 09:34

0 Answers0