sizeof()
operator gives the size of the datatype. So, sizeof(mattsentence)
will give you a value of 51
. Then, sizeof(mask)
will give you 51
again.
When you use that sizeof(mask)
as for
loop condition, you're basically going past the actual input values, thus pritning out garbage values.
What you want here is to use strlen()
to find out the actual valid length of the entered string.
So, basically you need to take care of
Point 1: replace sizeof
with strlen()
.
Point 2: Use of gets()
is dangerous. Please use fgets()
instead of gets()
.
Point 3: int main()
should be int main(void)
. Put an expilicit return
statement at the end of main()
. Good Practice.
The modified code should look like
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char mattsentence[51] = {0}; //always initalize local variables, here it's covering null termination , too.
fgets(mattsentence, 51, stdin); //fgets()
char mask[strlen(mattsentence) + 1]; // one more to store terminating '\0'
int i = 0, j = 0, k = 0;
j = strlen(mattsentence);
k = j;
for (i = 0; i < k; i++) // make use of k, don't call `strlen()` repeatedly
{
j = j - 1;
mask[i] = mattsentence[j];
printf("%c", mask[i]);
}
mask[i] = '\0'; // for proper string termination
printf("\n");
printf("%s\n", mask);
return 0; //added return statement
}