devxlogo

Fast, Efficient and Easy Way to Initialize Local Arrays

Fast, Efficient and Easy Way to Initialize Local Arrays

Fast, Efficient and Easy Way to Initialize Local ArraysBy 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 ''		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.

See also  lenso.ai - an AI reverse image search platform
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