In C language, how do I Initialize an array to 0 ?, Array Initialization

Source: Internet
Author: User

In C language, how do I Initialize an array to 0 ?, Array Initialization
How to initialize the array to 0?

Statement for declaring arrays in C language:

int arr[100];

In this way, the declared array stores random unknown data, which is garbage for users. In many cases, we need to initialize the array to zero to perform other operations.

The simplest way is to use a loop bar array to set all elements to 0:

int arr[100];int i = 0;for(i = 0 ; i < 100 ; i++)    arr[i] = 0;  //This will make all ZERO

 

We can also use other methods to initialize the array to 0:

1,Global variables and static variables are automatically set to 0 during initialization. If we declare a global variable, it will be changed to 0 before running.

int arr[1024]; // This is globalint main(void){    //statements}

2,For partial arrays, we also have the abbreviated initialization syntax. If an array is partially initialized, the uninitialized elements are automatically set to 0 of the corresponding type. This is automatically completed by the compiler. You can write as follows:

int main(void){    int arr[1024] = {0};  // This will make all ZERO    // statements}

Variable-length array (flexible array) is not available.

3,You can also use the memset function to initialize the array at the beginning of the program. This command is particularly useful after you have modified the array and want to reset it to all 0. (Applicable to variable-length arrays)

Header file: # include

int arr[1024];arr[5] = 67;memset(ZEROARRAY, 0, 1024); //This will reinitialize all to ZERO

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.