Still teaching myself C. This time, I'm trying to read a text from the keyboard using a function:
int read_line(char my_string[]) {
int characters;
fgets(my_string, sizeof(my_string), stdin);
characters = strlen(my_string);
printf("characters =%d, my_string=%s. \n", characters , my_string);
}
int main(int argc, char *argv[]) {
char line[MAX];
read_line(line);
}
When I enter in keyboard this:
abcdefg
I get this on the console:
characters =3, my_string=abc.
Why is C behaving in that way? What's the proper way to read a character string through a method?
You're using sizeof in your fputs. C can't determine the size of the buffer that way. To further explain, sizeof is used to determine the SIZEOF a type.
Example:
sizeof(short) = 2
sizeof(long) = 4
sizeof(char) = 1 (generally speaking, unless you compile for UNICODE)
Reason the original code did not work: When you use char[] as a parameter, it gets turned into a char * (a pointer to a char[]) which is why it has a sizeof of 4 (pointers are generally 4 bytes). If you use sizeof(line) in main() it will report the size properly due to the compiler changing the code to reflect that information at compile time.
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
int read_line(char my_string[]);
#define MAX 10
int _tmain(int argc, _TCHAR* argv[])
{
char line[MAX];
read_line(line);
return 0;
}
int read_line(char my_string[]) {
int characters;
fgets(my_string, MAX, stdin); <--FIX here
characters = strlen(my_string);
printf("characters =%d, my_string=%s. \n", characters , my_string);
return 0;
}