The problematic statement is this
printf("%ld",sizeof(user_input)); /* It desn't return the number of char stored in user_input */
as user_input
is a character pointer and sizeof pointer is always 4
byte on 32
bit machine and 8
bytes on 64 bit machine.
My suggestion is to use fgets()
instead of scanf()
. For e.g
Declare a character pointer and allocate memory.
char * user_input = NULL;
user_input = malloc(sizeof(*user_input) * MAX_BUF_SIZE); /* Instead of magic number use macro */
Do proper error handling of malloc()
. For e.g
if(user_input == NULL) {
fprintf(stderr, "memory allocation failed\n");
exit(-1);
}
Scan the input using fgets()
instead of scanf()
. for e.g
size_t retStrCspn = 0;
if(fgets(user_input, MAX_BUF_SIZE, stdin) != NULL) {
/* fgets success. next task is remove the trailing \n char read by fgets() */
user_input[retStrCspn = strcspn(user_input, "\n")] = 0; /* remove the trailing & use the return value */
}
Now print the length, don't use sizeof
, use the return value of strcspn()
for example
printf("%zu", retStrCspn);