Well, the first thing I notice, upon compiling and executing this, is
that it doesn’t let you enter the string. This is due to the way you’re
taking input:
printf("enter the size of the string ");
scanf("%d",&n);
printf("enter the string ");
fgets(a,n,stdin);
It runs scanf("%d",&n);
. So the user types, say, 6
, followed by the
enter key. Hokay, so scanf
looks at those characters 6\n
, takes the
6
, converts to a number, and n
ends up with a value of 6.
But that newline is still there. scanf
didn’t do anything with it
because it’s not numeric. So, when the code gets to here:
fgets(a,n,stdin);
It then reads that newline and thinks “Okay! The user entered an empty
string.” (Yes I know I’m being anthropomorphic, sue me.)
This sort of behavior is why I avoid using scanf
. I would code it this
way:
fgets(a, sizeof(a), stdin);
n = atoi(a);
printf("enter the string ");
fgets(a, sizeof(a), stdin);
Note that this also limits each fgets
to the size of the buffer,
avoiding potential buffer overflows. This is an important consideration
with working code, because a buffer overflow can easily lead to a
vulnerability that can be exploited to break security. Best to develop
good habits even with simple learning programs like this.
Note also that a better way to do this would be to simply read the
string by itself, then compute its length with strlen
.
At this point, it seems to be working correctly, so I won’t delve into
the rest of it. However, if you take my advice about computing the
length, there’s one more thing to be aware of. If you add this line
(temporarily, just for debugging purposes):
printf("%d\n", strlen(a));
You will see that you have one more character than you expect. That is
because fgets
retains the newline. So, we want to get rid of it:
a[strlen(a) - 1] = '\0';
This isn’t necessary if you use the value of n
, because then it will
just ignore the newline and use the n
characters preceding it. But it
would be necessary if you’re computing the length.