Is char string[5] = "Hello"; valid?

C language frequently asked question on string declaration: Is char string[5] = "Hello"; valid?
Submitted by IncludeHelp, on December 20, 2017

Yes, it is a valid declaration (some standard compilers may not support), but it should not be used. According to the string declaration rules, string must be terminated by NULL (0). In this declaration, an array of 5 elements will be created and all elements will be filled by ‘H’, ‘e’, ‘I’, ‘l’ and ‘o’ without terminating by NULL character.

Since, string will not be terminated properly, so it cannot be used with the printf, strcpy() etc.

How to fix this issue?

To fix this issue, size of array must be 6, the correct declaration will be: char string[6] = "Hello";




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.