Friday, February 12, 2010

How to Initialize Character Array Elements to '\0' in C++

Method 1:

#define MAX_PATH 100
..
char arr[ MAX_PATH ] = { 0 } ;

Method 2:
..
char arr[ MAX_PATH ] ;
memset ( arr, 0, MAX_PATH );

Both the above methods would initialize all the array elements to '\0' (NULL)

But I would prefer/suggest to use Method 1 over Method 2. Because
a) Using memset would require to include an additional header file like string.h or may be some other header file depending on the compiler.
c) It is an aditional function call which can be avoided while coding in domains like embedded or networking.
b) Using memset may mislead to manual errors by mistyping the input values.

0 comments:

Post a Comment

Categories

Blog Archive

  © Blogger template Webnolia by Ourblogtemplates.com 2009

Back to TOP