Thread: [Help] Strings in C

  1. #1
    Registered User
    Join Date
    Feb 2021

    Exclamation [Help] Strings in C

    #include <stdio.h>
    int main() {
        char str3[6] = {'h', 'e', 'l', 'l', 'o', '\0'};
        char str4[ ] = {'h', 'e', 'l', 'l', 'o'}; 
        printf("%s, %s", str3, str4);
        return 0;
    The output to this program is hello, hellohello
    why does it print that instead of hello, hello ?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    Because str4 doesn't have a \0 to mark the end of the string.

    So printf just keeps running through memory until it finds a \0.

    In your case, that just happened to be your str3.

    But it could have just as easily printed any random memory contents until it found a \0 (or crashed).
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 04-13-2017, 01:29 AM
  2. Comparing Python strings to C strings
    By hinesro in forum C Programming
    Replies: 0
    Last Post: 11-29-2015, 09:14 PM
  3. Replies: 2
    Last Post: 05-16-2012, 06:08 AM

Tags for this Thread