-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

Deanie
  • 2,316
  • 2
  • 19
  • 35
Aditya Varma
  • 330
  • 6
  • 16

3 Answers3

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'}
mattnewport
  • 13,728
  • 2
  • 35
  • 39
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'};
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
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.

7VoltCrayon
  • 662
  • 1
  • 7
  • 22