Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: All
May 6, 1998



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Fast, Efficient and Easy Way to Initialize Local Arrays

Fast, Efficient and Easy Way to Initialize Local Arrays By default, local data arrays created on the stack are not initialized; they contain garbage values. The easiest, most efficient and future-proof way to initialize them is as follows:
	void f() {
		char  name[100] = {0};  //all members initialized to '\0'
		float farr[1024] = {0}; //all members initialized to 0.0
		int   iarr[9999] = {0}; //all members initialized to 0.0
		void *pvarr[100] = {0};//all members initialized to NULL
And it even works for arrays of structs:
	struct A { char name[20]; 
			int age; /*other members*/ 

	void f() {
		A a[100] = {0};

The only exception is arrays of objects, which cannot be initialized like this if they have a user-defined constructor.
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