Reputation: 942
I am trying to reverse a string in C with pointers but the output is really weird. The logic seems good but I am not sure why it gets outputted like this. Here is the code:
#include <stdio.h>
#include <string.h>
int main()
{
char str[20], reverse_str[20], *pointer;
int i = 0;
printf("%s", "Enter any string: ");
scanf("%s", str);
pointer = str;
int string_length = strlen(pointer);
//int count = 0;
for (int i = string_length; i > 0; i--){
reverse_str[i -1] = *pointer;
pointer++;
}
printf("%d\n", string_length);
printf("Original string = %s\n", str);
printf("Reversed string = %s\n", reverse_str);
}
The output looks like this:
Enter any string: Hello
Original string = Hello
Reversed string = olleH╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠Hello
Upvotes: 1
Views: 82
Reputation: 15032
To print a string, the string needs a NUL-terminator \0
but reverse_str
doesn´t have one.
You need to set a \0
at the end of revers_str
, like:
reverse_str[string_length] = '\0';
to make it print the right output.
Upvotes: 1
Reputation: 3995
This is when the role of null terminator comes in which is often ignored as a silly bit of information by beginners.
In C, every string is terminated by a null character because there needs to be some way to know when a particular string ends starting from its initial location in memory. If you properly initialize the string or put in \0
appropriately then the string can be displayed as is. Otherwise every character in memory starting from the zeroth index of the string will be displayed until it encounters a null character. This is how a printf("%s", str)
works, in simple words.
You get that weird output because of this reason. This explains it much better.
Solution:
Add reverse_str[string_length] = '\0';
after you reverse your string using that for loop, so that your resultant string is properly null terminated.
Bonus:
And the reason why you got a considerably sane output is that you were lucky since the compiler allocated str
and reverse_str
close to each other in a direction such that even if you miss the null terminator on reverse_str
you hit the null terminator of str
.
Upvotes: 4