In the code below:
#include <stdio.h>
int main(){
char word[]="";
scanf("%s",word);
printf("%s: %d\n", word, sizeof(word));
}
Input:
Hello
Output:
Hello: 1
Why sizeof(word) prints the original size of word although it contains "Hello" after executing scanf() function instead of empty string.
I expect the output to be Hello: 6.
I understand that the issue is related to the way I am initializing the word array, but as you can see I want to avoid setting a static size to word and any string related header file.
I'm using VS Code and gcc (Rev2, Built by MSYS2 project) 13.2.0 compiler
C does not dynamically change the size of an array when you use
scanf.char word[]="";declares an array that is large enough to contain the array indicated by the string literal"".""means a string of zero characters terminate by a null byte. This string is represented by just one byte, the null byte. So an array for it contains one element.scanf("%s",word);asksscanfto read a string from the standard input stream and to write it to the arrayword. If there is are any non-white-space characters in the input, this will attempt to write beyond the end of the single-byte arrayword. Then the behavior is not defined by the C standard.If the program does continue,
sizeof(word)is the size of the array as it was defined, one byte. It is not the length of the string thatscanfscans.To read a string, you can start by defining
wordto be a large array, such aschar word[1024]. This is tolerable for a starting exercise, but you will learn better techniques for handling any input later.Then, to find the length of the string that is currently in the array, using
strlen, declared in the<string.h>header.sizeofgives the size of an object, which is the number of bytes reserved for it in memory.strlengives the length of the string defined by the values currently in the object. By analogy,sizeofgives the size of a box, andstrlensays how much is in the box at the moment.