Issue with printing the correct size of a string in C

72 views Asked by At

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

1

There are 1 answers

0
Eric Postpischil On BEST ANSWER

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); asks scanf to read a string from the standard input stream and to write it to the array word. If there is are any non-white-space characters in the input, this will attempt to write beyond the end of the single-byte array word. 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 that scanf scans.

To read a string, you can start by defining word to be a large array, such as char 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. sizeof gives the size of an object, which is the number of bytes reserved for it in memory. strlen gives the length of the string defined by the values currently in the object. By analogy, sizeof gives the size of a box, and strlen says how much is in the box at the moment.