Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
Dec 1, 1999

Array Initialization

Question:
I've always used memset() in C to do char array initialization, but in C++ is it normal/acceptable practice to initialize a char array during declaration using this syntax?

char Temp[10] = {0};

Answer:
In C++ you normally don't use arrays in the first place. You use a container class instead: e.g., std::vector. However, when you truly need a built-in array, such as:

char Temp[10];

you should avoid memset() if possible for two reasons: safety and maintenance. To demonstrate that, let's look at your example again:

char Temp[10] = {0};

What would happen if we changed the size of the array like this?

char Temp[20] = {0};

Nothing. The compiler would do the right thing and initialize the array properly. This is not the case with memset(), where you must specify the size of the array explicitly. Failing to do so can cause undefined behavior.

Note, however, that you cannot initialize arrays that are allocated from the free store this way. In this case, you cannot avoid calling memset().

DevX Pro
 
Comment and Contribute

 

 

 

 

 


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

 

 

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