2

I know the string in c will be terminated by a character \0.

However, if I do char a[5]="abcd\n" , where would \0 be?

Or do I need to reserve at least one position for \0, whenever I try to use char[] to store a string?

Thank you for any help!

7
  • 2
    You need to reserve one position for \0. So your array should be a[6]. Commented Feb 16, 2023 at 8:12
  • 7
    In your code, a is not a string! It's just a static byte buffer of length 5, but it misses the zero termination that would make it a string. C allows this (in C++ this initialisation would be invalid). Commented Feb 16, 2023 at 8:13
  • @kiner_shah Thank you, and I was also wondering what will happen if I insist to use a[5]? Can I still normally use functions for string? Commented Feb 16, 2023 at 8:13
  • 3
    If your "string" is not null terminated, it's not a string. Commented Feb 16, 2023 at 8:15
  • 1
    As @KonradRudolph says, the array is not a string in the sense that all standard C string functions expects it to be, because it doesn't have the terminator. So if you pass it to e.g. strlen then you will get undefined behavior. Commented Feb 16, 2023 at 8:15

1 Answer 1

3

You should do:

char a[]="abcd\n";

without specifying the size to let compiler figure out the buffer size. The actual buffer will have size of 6 to accommodate your 5 bytes + 1 byte for terminating zero. When you type "something" without assignment, compilaer puts that string in a dedicated place in the program with at least 1 zero byte after the last character.

Writing char a[5]="abcd\n" is a bad practice because it will cause functions like strcpy() to act in undefined manner as your variable 'a' is not a c string, but just a buffer of characters, which by chance seem to be all printable/visible + terminating \n

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.