Reputation: 1387
I am studying for an interview and found this question a bit bewildering. Would appreciate your advice.
What is not initialized by default?
- The last variable of a static array in which the first variables are explicitly initialized in a statement.
- Dynamic array members assigned using a
calloc
function.- Global variable.
- All data provided here is initialized by default.
- The current cursor location when a file is open.
- A static variable.
- The last character in a static character set.
I think the answer is #1 but not sure about the explanation.
Upvotes: 1
Views: 123
Reputation: 768
calloc
zero the memory it points to.append
mode (a
in fopen
) the cursor location will be 0. In append
mode it will be the length of the file.char
array, and like any other array, when initialized the last char
, if uninitialized, will be 0.
In the case of a char
array, the last char
will be the NULL byte and its intention is to be 0 to mark the end of the string.As you can see, all the options are initialized by default so the answer is 4.
If you are not sure, always check your questions with a simple code:
#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
*/
}
Upvotes: 2