简体   繁体   English

int数组元素未在C中初始化为零

[英]int array element not initialized to zero in C

I created an array of 10 elements in C inside of main and declared values for only some of the elements. 我在C的main内部创建了一个由10个元素组成的数组,仅对其中一些元素声明了值。 When printing out the array I noticed that one of the elements, which was left untouched, was not initialized to zero. 当打印出数组时,我注意到未被触动的元素之一未初始化为零。 Instead, it was initialized to a different large value every time (ie 1491389216 ). 而是每次都将其初始化为一个不同的较大值(即1491389216 )。 I then commented out all of my code and just left the array as I initially declared it. 然后,我注释掉了所有代码,并在最初声明时离开了数组。

When running the code, the first 8 elements of the array were initialized to zero, the 9th element in the array was being initialized to a large value (like 1491389216 ) which changed every time, and the last element was consistently being initialized to the same non-zero number. 运行代码时,将数组的前8个元素初始化为零,将数组中的第9个元素初始化为较大的值(如1491389216 ),该值每次都更改,并且最后一个元素始终被初始化为相同的值非零数字。

Does anyone have any idea why this is happening? 有谁知道为什么会这样吗?

Local (automatic) arrays are not initialized unless you explicitly initialize them. 除非您显式初始化本地(自动)数组,否则不会对其进行初始化。 Otherwise they contain whatever random data already occupies the memory. 否则,它们将包含已占用内存的任何随机数据。

If you want to zero out all of the elements when declaring the array, you can do this: 如果要在声明数组时将所有元素归零,则可以执行以下操作:

int arr[10] = {0};

Or: 要么:

int arr[10] = {};

Depending on your compiler (GCC allows this, unless you specify -pedantic ). 取决于您的编译器(GCC允许这样做,除非您指定-pedantic )。

Or, just use memset() instead: 或者,只需使用memset()

int arr[10];
memset(arr, 0, sizeof(arr));

Similarly, memory allocated by malloc() — or extended by realloc() — is not initialized; 同样,由malloc()分配的malloc()或由realloc()扩展的内存也不会初始化。 use calloc() to zero-initialize such data: 使用calloc()对这些数据进行零初始化:

int *arr = (int*) calloc(10, sizeof(int));
...
free(arr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM