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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.