-1

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
jonasPamm
  • 87
  • 9
  • 5
    `sizeof` is evaluated at compile time. Are you perhaps interested in `strlen`? –  Nov 16 '21 at 15:21
  • 1
    only thing you did wrong is use `"%i"` to print `sizeof`, [use `"%zu"` instead](https://stackoverflow.com/questions/27296011/correct-format-specifier-for-return-value-of-sizeof-in-c). Your expectation of `sizeof` is wrong, it should indeed print out 100, that's the size of `toFind`. – yano Nov 16 '21 at 15:23
  • If you do use `strlen` you might notice the size is off by one more than what you expect. That is because `fgets` includes the newline if it is there. – 001 Nov 16 '21 at 15:26

3 Answers3

1

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.

user253751
  • 57,427
  • 7
  • 48
  • 90
0

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.

ikegami
  • 367,544
  • 15
  • 269
  • 518
0

For starters you have to use the conversion specifier %zu to output a value of the type size_t (the operator sizeof returns values 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 declared in the header <string.h> like

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

//...


printf( "%zu\n", 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\n", strlen( toFind ) );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335