devxlogo

Array Initialization

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().

See also  11 Effective Keyword Research Tools and Techniques
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist