How to initialize an array to something in C without a loop?

后端 未结 7 1674
灰色年华
灰色年华 2021-01-02 06:58

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

相关标签:
7条回答
  • 2021-01-02 07:12
    int arr[10][10] = {0}; // only in the case of 0
    
    0 讨论(0)
  • 2021-01-02 07:13

    Besides the initialization syntax, you can always memset(arr, 0, sizeof(int)*10*10)

    0 讨论(0)
  • 2021-01-02 07:18

    Defining a array globally will also initialize with 0.

    
        #include<iostream>
    
        using namespace std;
    
        int ar[1000];
        
        int main(){
    
    
            return 0;
        }
    
    
    0 讨论(0)
  • 2021-01-02 07:19
    int myArray[2][2] = {};
    

    You don't need to even write the zero explicitly.

    0 讨论(0)
  • 2021-01-02 07:26

    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 ints. But an int that's all 0 bytes will always have the value 0.

    0 讨论(0)
  • 2021-01-02 07:30

    int arr[10][10] = { 0 };

    0 讨论(0)
提交回复
热议问题