thephysicsguy thephysicsguy - 3 months ago 16
C Question

fgets generates random characters in the string

I am writing a simple mathematical function reader in C and compiling with gcc-5.
When I run the following code

#include <stdio.h>
#include <stdlib.h>


int read_input(char* func)
{
printf("Please enter the function: ");
if (fgets(func, sizeof func, stdin)) {
printf("The function is %s.\n",func);
}
return 0;
}

int main ()
{
char func[64];
read_input(func);
for(int i = 0; i < sizeof(func); i++) {
printf("Char %d in func is %c\n", i, func[i]);
}
return 0;
}


I get

Char 0 in func is h
Char 1 in func is e
Char 2 in func is l
Char 3 in func is l
Char 4 in func is o
Char 5 in func is

Char 6 in func is
Char 7 in func is
Char 8 in func is
Char 9 in func is
Char 10 in func is
Char 11 in func is
Char 12 in func is
Char 13 in func is
Char 14 in func is
Char 15 in func is
Char 16 in func is
Char 17 in func is
Char 18 in func is
Char 19 in func is
Char 20 in func is
Char 21 in func is
Char 22 in func is
Char 23 in func is
Char 24 in func is �
Char 25 in func is
Char 26 in func is @
Char 27 in func is
Char 28 in func is
Char 29 in func is
Char 30 in func is
Char 31 in func is
Char 32 in func is
Char 33 in func is
Char 34 in func is
Char 35 in func is
Char 36 in func is
Char 37 in func is
Char 38 in func is
Char 39 in func is
Char 40 in func is
Char 41 in func is
Char 42 in func is
Char 43 in func is
Char 44 in func is
Char 45 in func is
Char 46 in func is
Char 47 in func is
Char 48 in func is �
Char 49 in func is
Char 50 in func is @
Char 51 in func is
Char 52 in func is
Char 53 in func is
Char 54 in func is
Char 55 in func is
Char 56 in func is
Char 57 in func is
Char 58 in func is @
Char 59 in func is
Char 60 in func is
Char 61 in func is
Char 62 in func is
Char 63 in func is


Why am I getting a new line character and how I can I not get it in my fgets? Also what are all those weird characters that I am getting?

Answer
if (fgets(func, sizeof func, stdin))

The problem is that arrays, when passed to functions, decay into a pointer to their first element. You are passing a char array, which then decays into a pointer to char. Thus, with the sizeof statement, you are simply getting the size of a pointer on the current machine. The solution to this is to pass the number of elements as the argument to read_input, and use that as the second argument of fgets. Or, use strlen.