I've been thinking what is the difference between
char[] = "hello world"
and
char[20] = "hello world"
I tried to write this short code:
#include <stdio.h>
#include <stdlib.h>
int main(){
int i;
char str[20] = "hello world";
for( i = 0; i<20; i++){
if(str[i]=='\n')
printf("\nExit character newline");
else if(str[i]=='\0')
printf("\nNull terminated..");
else
printf("\nCur: %c", str[i]);
}
return 0;
}
which outputs:
Cur: h
Cur: e
Cur: l
Cur: l
Cur: o
Cur:
Cur: w
Cur: o
Cur: r
Cur: l
Cur: d
Null terminated..
Null terminated..
Null terminated..
Null terminated..
Null terminated..
Null terminated..
Null terminated..
Null terminated..
Null terminated..
On the otherhand, when I do not specifically define the array size and just use
char[] = "hello world"
It gives me this output:
Cur: h
Cur: e
Cur: l
Cur: l
Cur: o
Cur:
Cur: w
Cur: o
Cur: r
Cur: l
Cur: d
Null terminated..
Cur:
Null terminated..
Null terminated..
Null terminated..
Cur:
Cur:
Cur: a
Null terminated..
I am confused of the above output. Doesnt char[] = "hello world" just end up with 12 elements with a null terminator filling in the last element? Also, if I printf char with %s, will my assumption be correct?