Reputation: 3
I am currently confused about the execution of my basic c program to reverse a string. I use pointers. Keep in mind that my procedure is most definitely not the most efficient, I simply want to experiment pointers. The problem I have is the following:
// initialize variables
char *sentence = malloc(256);
char *answer = malloc(256);
// ask user for input
printf("please enter sentence\n");
scanf("%s", sentence);
// loop to reverse the "sentence" string
for (int index = count; index >=0; index--) // count has been determined as the length of the string "sentence" previously
{
reversed = &sentence[index]; // pointer reversed points to last location of pointer sentence
printf("\n ** %c", *reversed);
reversed++; // incremend reversed by 1
}
printf("\n%s", reversed); // prints the cahr pointer reversed as string
Console result
If you cannot open the image, what I get is all the character printed in reverse order in the printf in the loop. However the final printf gives a weird result: ( If my sentence is bonjour) \n
** r
** u
** o
** j
** n
** o
** b
.
onjour <-- This is what I don't understand.
Thank you for your help, very appreciated.
Upvotes: 0
Views: 269
Reputation: 1
reversed = &sentence[index];
That's wrong, I think.
reversed = sentence[index];
would be right. Anyway that code is messy everywhere.
Upvotes: -1
Reputation: 726987
The code that prints the string character-by-character in reverse does not store the result in the answer. You need to do it by first pointing reversed
to answer
, and then adding characters to it as you progress through your loop:
char *reversed = answer;
for (int index = count; index >=0; index--) {
*reversed = sentence[index];
printf("\n ** %c", *reversed);
reversed++;
}
*reversed = '\0';
printf("\n%s", answer);
Upvotes: 2