有关C中默认初始化的问题

时间:2020-08-02 07:24:13

标签: c default-initialization

我正在研究面试,发现这个问题有些令人困惑。非常感谢您的建议。

默认情况下未初始化什么?

  1. 静态数组的最后一个变量,其中的第一个变量在语句中被显式初始化。
  2. 使用calloc函数分配的动态数组成员。
  3. 全局变量。
  4. 默认情况下,此处提供的所有数据均已初始化。
  5. 打开文件时的当前光标位置。
  6. 静态变量。
  7. 静态字符集中的最后一个字符。

认为答案是#1,但不确定解释。

1 个答案:

答案 0 :(得分:2)

  1. 在静态数组(或任何数组)中,当它被显式初始化时,所有未初始化的变量的值将为0。
  2. calloc将其指向的内存归零。
  3. 默认情况下,全局变量的值为0。
  4. 占位符(这只是意味着所有其他选项都已初始化)。
  5. 如果未在append模式下打开(a中的fopen),则光标位置将为0。在append模式下,它将是文件的长度。 / li>
  6. 静态变量的默认值为0。
  7. 静态字符集(如果我理解正确的话)是一个char数组,并且像任何其他数组一样,初始化后,最后一个char(如果未初始化)将为0。 对于char数组,最后一个char将是NULL字节,其目的是将0标记为字符串的结尾。

如您所见,所有选项默认情况下都已初始化,因此答案为4。

如果不确定,请始终使用简单的代码检查问题:

#include <stdio.h>
#include <stdlib.h>

void test1()
{
    static int arr[5] = { 1,2,3,4 };
    printf("Last variable is %d\n", arr[4]);
}

void test2()
{
    int* arr = (int*)calloc(5, sizeof(int));
    int b = 1;
    for (int i = 0; b && i < 5; i++)
        if (arr[i])
            b = 0;
    if (b) puts("Calloc zero all elements");
    else puts("Calloc doesn't zero all elements");
}

int test3_arg;

void test3()
{
    printf("Global variable default value is %d\n", test3_arg);
}

void test5()
{
    FILE* file = fopen(__FILE__, "r");
    printf("The current cursor location is %ld\n", ftell(file));
    fclose(file);
}

void test6()
{
    static int arg;
    printf("Static variable default value is %d\n", arg);
}

void test7()
{
    static char arg[] = "hello";
    printf("The last character is %d\n", arg[5]); //last one will be the NULL byte (0)
}

int main()
{
    test1();
    test2();
    test3();
    test5();
    test6();
    test7();

    return 0;

    /*
     * Output:
    Last variable is 0
    Calloc zero all elements
    Global variable default value is 0
    The current cursor location is 0
    Static variable default value is 0
    The last character is 0
     */
}