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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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
	}//f()
And it even works for arrays of structs:
 
	struct A { char name[20]; 
			int age; /*other members*/ 
		  };

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

	}//f()
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.

 

 

Sitemap
×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date