I am currently learning C, and so I wanted to make a program that asks the user to input a string and to output the number of characters that were entered, the code compiles fin
This line:
char i[] = "";
is equivalent to:
char i[1] = {'\0'};
The array i
has only one element, the program crashes because of buffer overflow.
I suggest you using fgets()
to replace scanf()
like this:
#include
#define MAX_LEN 1024
int main(void)
{
char line[MAX_LEN];
if (fgets(line, sizeof(line), stdin) != NULL)
printf("%zu\n", strlen(line) - 1);
return 0;
}
The length is decremented by 1
because fgets()
would store the new line character at the end.