guitar_geek
guitar_geek

Reputation: 498

character array printing output

I am trying to understand outputs of printing character arrays and it is giving me variable outputs on ideone.com(C++ 4.3.2) and on my machine (Dev c++, MinGW compiler)

1)

#include<stdio.h>
main()
{
    char a[] = {'s','t','a','c','k','o'};
    printf("%s ",a);
}

It prints "stacko" on my machine BUT doesn't print anything on ideone

2)

#include<stdio.h>
main()
{
    char a[] = {'s','t','a','c','k','o','v','e'};
    printf("%s ",a);
}

on ideone : it prints "stackove" only the first time then prints nothing the subsequent times when i run this program on my dev-c : it prints "stackove.;||w" what should be the IDEAL OUTPUT when I try to print this kind of character array without any '\0' at the end , it seems to give variable outputs everywhere . please help !

Upvotes: 0

Views: 2561

Answers (1)

ajay
ajay

Reputation: 9680

%s conversion specifier expects a string. A string is a character array containing a terminating null character '\0' which marks the end of the string. Therefore, your program as such invokes undefined behaviour because printf overruns the array accessing memory out of the bound of the array looking for the terminating null byte which is not there.

What you need is

#include <stdio.h>

int main(void)
{
    char a[] = {'s', 't', 'a', 'c', 'k', 'o', 'v', 'e', '\0'};
    //                                                    ^
    // include the terminating null character to make the array a string

    // output a newline to immediately print on the screen as
    // stdout is line-buffered by default
    printf("%s\n", a);

    return 0;
}

You can also initialize your array with a string literal as

#include <stdio.h>

int main(void)
{
    char a[] = "stackove";  // initialize with the string literal
    // equivalent to
    // char a[] = {'s', 't', 'a', 'c', 'k', 'o', 'v', 'e', '\0'};

    // output a newline to immediately print on the screen as
    // stdout is line-buffered by default
    printf("%s\n", a);

    return 0;
}

Upvotes: 2

Related Questions