As I was practicing the use of fgets() to read string from input, I found myself copying the same piece of code over and over, so I created a function to call every time I need to do it. Here is a simple example of how it works:
#include <stdio.h>
#include <string.h>
void GetLine(char str[]) {
// This is the function, I added a printf() to better show what's happening
printf("Maximum size of the string in GetLine: %i\n", sizeof(str));
fgets(str, sizeof(str), stdin);
// This is for clearing the newline character
// either from the recently received string or from the input buffer
if (str[strlen(str)-1] == '\n')
str[strlen(str)-1] = '\0';
else {
char DISCARD;
while((DISCARD = getchar())!='\n' && DISCARD != EOF);
}
}
int main() {
char MyString[51];
printf("Maximum size of the string in main: %i\n", sizeof(MyString));
GetLine(MyString);
printf("Contents of the string: >%s<\n", MyString);
return 0;
}
Here's the output:
Maximum size of the string in main: 51
Maximum size of the string in GetLine: 4
My name is Pedro
Contents of the string: >My <
Notice how str[]
only have 4 spaces, instead of being the size of the string passed to it.
The workaround for this is pretty easy: make GetLine()
also receive an integer that holds the size of the string, so it can read the correct number of characters without depending of sizeof(str)
.
However I'd really like to know both why this happens(the 4 space thing) and if I can fix this method somehow(make char str[]
the same size as the string passed as argument).
Thanks in advance.