0

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?

3
  • 4
    Strings in C are arrays of characters terminated by a null character. Your second char a[] isn't. Commented Nov 29, 2022 at 23:33
  • sorry, i forgot the apostrophe. i fixed the question. Commented Nov 29, 2022 at 23:39
  • 1
    It is possible for printf to also print the array char a[] = {'c','a','r'}; If you want to print a char array that is not necessarily terminated by a null character, then you must tell printf the 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 change printf("%s", a); to printf("%.3s", a);. See the documentation for printf for further information. However, it is generally better to always use a null terminator. Commented Nov 29, 2022 at 23:46

1 Answer 1

1

The %s specifier of printf() expects a char* pointer to a null-terminated string.

In the first case, a and b are both null-terminated. Initializing a char[] array of unspecified size with a string literal will include the literal's null-terminator '\0' character at the end. Thus:

char a[] = "car";

is equivalent to:

char a[] = {'c', 'a', 'r', '\0'};

In the second case, a is NOT null-terminated, leading to undefined behavior, as printf("%s", a) will read past the end of a into surrounding memory until it eventually finds a '\0' character. It just happens that, in your case, b exists in that memory following a, but that is not guaranteed, the compiler can put b wherever it wants.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.