-5

I know I am supposed to put '/o' at end of character array but When I want to print "printf ("%s\n", kk);" , it gives "abcdepqrst". Why is this happening? This is the program I am executing.

#include<stdio.h>
int main()
{

char kk[]={'a','b','c','d','e'};
char s[]="pqrst";

printf("%s\n",s);

printf("%s\n",kk);

}

Output:

pqrst

abcdepqrst

I tried reversing the order in which I declare the array by declaring array 's' before array 'kk' here, ideone link, but I am still getting the same output. I think it has something do with how ideone allocates memory to variables.

#include<stdio.h>
int main()
{
char s[]="pqrst";
char kk[]={'a','b','c','d','e'};


printf("%s\n",s);

printf("%s\n",kk);

}

Output:

pqrst

abcdepqrst

1

3 Answers 3

4

The printf() function expects a null terminated string but you are passing a character array with no null terminator. Try changing your array to:

char kk[]={'a','b','c','d','e','\0'};

When you use string literal syntax to initialize your s array, the null terminator is automatically added:

char s[] = "pqrst"; // s is {'p','q','r','s','t','\0'}
5
  • Please check the edit. Aug 27, 2015 at 20:23
  • What's the point of all of these downvotes?
    – Eugene Sh.
    Aug 27, 2015 at 20:24
  • @EugeneSh.; Beware of ghost souls!!
    – haccks
    Aug 27, 2015 at 20:24
  • Is the behaviour undefined as said by @juanchopanza. Aug 27, 2015 at 20:26
  • @c0de222 yes, it is undefined behaviour, typically you will just see whatever is in memory after your non-terminated string until there happens to be a 0 byte or you cause an access violation. In your case it happens the compiler has chosen to place your other string s immediately after kk in memory. Aug 27, 2015 at 20:28
4

kk is not null-terminated, so printf doesn't know where to stop. Invoking printf on a string that is not null-terminated is undefined behaviour (UB). That means you cannot expect any particular outcome from your program. What you see is one manifestation of UB.

You need to add a null-terminator:

char kk[]={'a','b','c','d','e', '\0'};
3
  • Okay. So we can not expect a particular output? Aug 27, 2015 at 20:25
  • 2
    @c0de222 Right, UB means pretty much anything can happen. Aug 27, 2015 at 20:25
  • But practically, it will just print everything in the memory starting at kk until the first zero is encountered. Which in your case at the end of s. And as the s and kk are allocated on stack, it is going "backwards".
    – Eugene Sh.
    Aug 27, 2015 at 20:28
0

You need to add a '\0' character to kk as it's last element like so:

char kk[]={'a','b','c','d','e','\0'};

or printf is just going to run off the end of the array.

3
  • Please check the edit. Aug 27, 2015 at 20:23
  • I commented on your question with a link to an answer which clears the concept. Aug 27, 2015 at 20:24
  • Thanks for the link. Aug 27, 2015 at 20:32

Not the answer you're looking for? Browse other questions tagged or ask your own question.