#include<stdio.h>
void m(int *p){
int i=0;
for(int i=0;i<5;i++)
printf("%d",p[i]);
}
int main(){
int a[5]={4,5,6};
m(a);
}
I expect the output will be 4 5 6 junkValue junkValue ,but the actual output is 4 5 6 0 0
#include<stdio.h>
void m(int *p){
int i=0;
for(int i=0;i<5;i++)
printf("%d",p[i]);
}
int main(){
int a[5]={4,5,6};
m(a);
}
I expect the output will be 4 5 6 junkValue junkValue ,but the actual output is 4 5 6 0 0
In section "6.7.9 Initialization" of the standard it says:
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
As int
is zero initialized when used as static objects, the code:
int a[5]={4,5,6};
is really the same as
int a[5]={4,5,6,0,0};
So there will be no "junk values" printed. It will (and must) print the two zeros.
In C there is no partial initialization.
An object either is not initialized or is fully 100% initialized (to 0
of the right kind in the absence of any other initializer)
int a[5] = {4, 5, 6}; // a[0] = 4, ..., a[3] = a[4] = 0;
int b[5]; // uninitialized
b[0] = 4;
b[1] = 5;
b[2] = 6;
m(b); // b[3] and b[4] have not been initialized/assigned
// accessing them is UB
int a[5]={4,5,6}; is a partially initialized array. Uninitialized array elements a[3], a[4] are initialized to zero. So this is expected behavior.