How to initialize an array to something in C without a loop?
Lets say I have an array like
int arr[10][10];
Now 开发者_如何学运维i want to initialize all elements of this array to 0. How can I do this without loops or specifying each element?
Please note that this question if for C
The quick-n-dirty solution:
int arr[10][10] = { 0 };
If you initialise any element of the array, C will default-initialise any element that you don't explicitly specify. So the above code initialises the first element to zero, and C sets all the other elements to zero.
Besides the initialization syntax, you can always memset(arr, 0, sizeof(int)*10*10)
int arr[10][10] = {0}; // only in the case of 0
You're in luck: with 0, it's possible.
memset(arr, 0, 10 * 10 * sizeof(int));
You cannot do this with another value than 0, because memset
works on bytes, not on int
s. But an int
that's all 0
bytes will always have the value 0
.
int myArray[2][2] = {};
You don't need to even write the zero explicitly.
Defining a array globally will also initialize with 0.
#include<iostream>
using namespace std;
int ar[1000];
int main(){
return 0;
}
int arr[10][10] = { 0 };
精彩评论