C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » C programming language

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";

Liked this article? Do share with your friends :)

Are you a blogger? Join our Blogging forum.