Reputation: 3473
In C Language i'm creating a array ( 2 Dimensional ) in which all the elements are zeros
I do it the following way :
int a[5][5],i,j; //a is the required array
for(i=0;i<5;i++)
for(j=0;j<5;j++)
a[i][j]=0;
I know some other way also :
int a[5][5]={0};
Are both the same or is there any difference ??
What should be preferred ??
Thank you !
Upvotes: 3
Views: 1297
Reputation: 106002
I would prefer latter one if I do not want to over stress my eyes (and my compiler too).
Upvotes: 0
Reputation:
Second one is useful.
The first one uses for
loop, so it takes time.
There are other ways in which you can initialize an arrray...
int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }; // All elements of myArray are 5
int myArray[10] = { 0 }; // Will initialize all elements to 0
int myArray[10] = { 5 }; // Will initialize myArray[0] to 5 and other elements to 0
static int myArray[10]; // Will initialize all elements to 0
/************************************************************************************/
int myArray[10];// This will declare and define (allocate memory) but won’t initialize
int i; // Loop variable
for (i = 0; i < 10; ++i) // Using for loop we are initializing
{
myArray[i] = 5;
}
/************************************************************************************/
int myArray[10] = {[0 ... 9] = 5}; // This works in GCC
memset(myArray, 0, sizeof(myArray));
Upvotes: 3
Reputation: 22542
Both ways have the same effect, but the second one will generally be faster because it allows the compiler to optimise and vectorise that code.
Another widely accepted way (also optimisable) is
memset(a, 0, sizeof(a));
Upvotes: 6
Reputation: 8861
The second method is more concise. Also consider:
memset(&a, 0, sizeof(a));
Upvotes: 6