Hi i am fairly new in C language and i was trying to understand the strings. As i know, strings are just an array of characters and there shouldn't be a difference between char a[]= "car" and char a[] = {'c','a','r'}.
When i try to print the string as:
char a[] = "car";
char b[] = "testing the cars";
printf("%s", a);
the output is just car and there's no problem.But when i try to print it as:
char a[] = {'c','a','r'};
char b[] = "testing the cars";
printf("%s", a);
it's printing the b too. Can you explain what's the reason of it?
char a[]isn't.printfto also print the arraychar a[] = {'c','a','r'};If you want to print achararray that is not necessarily terminated by a null character, then you must tellprintfthe maximum length of the array to print, so that it does not try to access the array out of bounds while searching for the end of the string. In this case, you would have to changeprintf("%s", a);toprintf("%.3s", a);. See the documentation for printf for further information. However, it is generally better to always use a null terminator.