Consider following case:
#include<stdio.h>
int main()
{
char A[5];
scanf("%s",A);
printf("%s",A);
}
My question is if char A[5]
contains only two characters. Say "ab", then A[0]='a'
, A[1]='b'
and A[2]='\0'
.
But if the input is say, "abcde" then where is '\0'
in that case. Will A[5]
contain '\0'
?
If yes, why?
sizeof(A)
will always return 5 as answer. Then when the array is full, is there an extra byte reserved for '\0'
which sizeof()
doesn't count?
character arrays in c are merely pointers to blocks of memory. If you tell the compiler to reserve 5 bytes for characters, it does. If you try to put more then 5 bytes in there, it will just overwrite the memory past the 5 bytes you reserved.
That is why c can have serious security implementations. You have to know that you are only going to write 4 characters + a \0. C will let you overwrite memory until the program crashes.
Please don't think of char foo[5] as a string. Think of it as a spot to put 5 bytes. You can store 5 characters in there without a null, but you have to remember you need to do a memcpy(otherCharArray, foo, 5) and not use strcpy. You also have to know that the otherCharArray has enough space for those 5 bytes.
As already pointed out - you have to define/allocate an array of length N + 1 in order to store N chars correctly. It is possible to limit the amount of characters read by scanf. In your example it would be:
in order to read max. 4 chars from stdin.
\0 is an terminator operator which terminates itself when array is full if array is not full then \0 will be at the end of the array when you enter a string it will read from the end of the array
You'll end up with undefined behaviour.
As you say, the size of
A
will always be 5, so if you read 5 or morechar
s,scanf
will try to write to a memory, that it's not supposed to modify.And no, there's no reserved space/char for the
\0
symbol.the null character is used for the termination of array. it is at the end of the array and shows that the array is end at that point. the array automatically make last character as null character so that the compiler can easily understand that the array is ended.
Any string greater than 4 characters in length will cause
scanf
to write beyond the bounds of the array. The resulting behavior is undefined and, if you're lucky, will cause your program to crash.If you're wondering why
scanf
doesn't stop writing strings that are too long to be stored in the arrayA
, it's because there's no way forscanf
to knowsizeof(A)
is 5. When you pass an array as the parameter to a C function, the array decays to a pointer pointing to the first element in the array. So, there's no way to query the size of the array within the function.In order to limit the number of characters read into the array use