Why initializing an array with 0 clears the entire buffer?

时间:2019-04-08 13:25:33

标签: c initialization

I am initializing my array, with 0, and I have the buffer clean, what happens to the bits? For example, when I initialize with 'a', not the same, if it were with memset the whole buffer would be filled with 'a'?

#include <stdio.h>
#include <string.h>

int main(void) {

    char buffer[256] = {0}, array[256] = {'a'};
    char array1[256];
    memset(array1, 'a', sizeof(array1));

    printf("%c\n%c\n%c\n", buffer[1], array[1], array1[1]);

    return 0;

}

3 个答案:

答案 0 :(得分:2)

If the initialiser does not provide enough elements to initialise the complete variable the rest is initialised as if the variable were declare globally, that is:

  • integers to 0
  • floats to 0.
  • pointers to NULL.

In your particular example the remaining elements of the char-array array will be following the above rule for integers.

答案 1 :(得分:2)

The initialization in the case of array[256] = {'a'}; happens as per this rule:

6.7.9 Initialization
...
21 If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

So only the first element of array will have the value 'a'.

But in the case of memset function,

void *memset(void *s, int c, size_t n);

the function copies the value of c (converted to an unsigned char) into each of the first n characters of the object pointed to by s.

So in this case all the elements of array1 will have the value 'a'.

答案 2 :(得分:0)

输入函数时,在这种情况下,main()会将堆栈增加堆栈框架所需的数量,在堆栈框架中,所有auto(函数内部声明的变量)的空间为以及此处不相关的其他信息。 因此,在这种情况下,您编写

char array[256]

当程序进入函数时,堆栈将增加足够的空间以为数组中的256个字符腾出空间,数组中字符的值未定义,可能是内存中的该区域先前被写入另一个不再需要它的函数或程序,所以我们不知道其余数组的值是什么。

写作时

char array[256] = {'a'}

它等效于:

char array[256];
array[0] = 'a';

在这种情况下,我们尚未定义数组其余部分中的内容

这样做的时候

memset(array, 'a', sizeof(array))

CPU将需要遍历整个数组并将数组中的每个字符初始化为'a',从而以使用更多CPU的代价为数组中的所有内容创建一个已知值。