我正在研究面试,发现这个问题有些令人困惑。非常感谢您的建议。
默认情况下未初始化什么?
- 静态数组的最后一个变量,其中的第一个变量在语句中被显式初始化。
- 使用
calloc
函数分配的动态数组成员。- 全局变量。
- 默认情况下,此处提供的所有数据均已初始化。
- 打开文件时的当前光标位置。
- 静态变量。
- 静态字符集中的最后一个字符。
我认为答案是#1,但不确定解释。
答案 0 :(得分:2)
calloc
将其指向的内存归零。append
模式下打开(a
中的fopen
),则光标位置将为0。在append
模式下,它将是文件的长度。 / li>
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
*/
}