Home > OS >  sizeof doesn't give back the real length of an input
sizeof doesn't give back the real length of an input

Time:11-16

I tried to test sizeof in my programm but it doesn't work.

char toFind[100];
fgets(toFind, sizeof(toFind), stdin);
printf(" %i", sizeof(toFind));

And what ever I put in it prints out 100. What did I wrong.

CodePudding user response:

toFind is an array of 100 chars. Each char is 1 byte. So toFind is 100 bytes.

Therefore sizeof(toFind), which tells you how many bytes are in toFind, is 100. There is no problem. sizeof is working correctly.

You might be interested in strlen(toFind) which tells you how many bytes are before the first 0 byte. Since fgets puts a 0 byte after the characters it reads, this tells you how many characters fgets read.

CodePudding user response:

sizeof returns the size of a variable. It has nothing to do with what it contains. In fact, it's calculated at compile-time.

fgets populates the variable with a NUL-terminated string. As such, you can use strlen to find its length. Note that since this is the only way to know how much fgets read in, it makes it unsuitable for data that might contains NUL characters.

By the way, the correct format specifier for size_t (the type returned by sizeof) is %zu.

CodePudding user response:

For starters you have to use the conversion specifier %zu to output a value of the type size_t instead of the conversion specifier %i

printf(" %zu", sizeof(toFind));

The operator sizeof returns the size of the array toFind that is declared as

char toFind[100];

The size of the array does not depend on what is stored in the array.

Instead you need to use the function strlen like

#include <string.h>
#include <stdio.h>

//...


printf(" %zu", strlen(toFind));

But before using the function you should remove the new line character '\n' that can be appended to the entered string by the function fgets.

#include <string.h>
#include <stdio.h>

//...


toFind[ strcspn( toFind, "\n" ) ] = '\0';
printf(" %zu", strlen(toFind));
  •  Tags:  
  • c
  • Related