Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: All
Sep 25, 2000

Hardcoded Char Arrays

Does your C++ compiler accept the following code?

char s[3]="abc"; // illegal in C++, no place for '\0'

The standard requires that the size of a char array initialized with a literal string be sufficiently large to store a terminating null character. In other words, the declaration of s should be flagged as a compilation error because it contains only three positions instead of four. Unfortunately, the rules regarding static char arrays in C are less restrictive. Therefore, such a declaration is valid in C. Many C++ compilers still follows the old C rules and accept the declaration above when they shouldn't. Using such an array is likely to cause undefined behavior because most functions that manipulate strings expect a null-terminated array.

Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date