Reputation: 379
I want to follow the given code:
#include <stdio.h>
#include <string.h>
int main() {
char m[100]="Mirror",*p,*q;
int i;
p=m;
q=p+strlen(m);
printf("%d\n",strlen(m));
printf("The value of s is: %c\n", &p);
for(i=strlen(m)-1;i>=0;i--)
{
*q++=*(p+i);
*q=0;
}
puts(m);
return 0;
}
Here what i have started:
can someone show me how to follow the given variable so I will be able to solve similar questions?
I want to write a table that shows the value in each step. where the pointer points
Upvotes: 0
Views: 71
Reputation: 31296
The best way is to learn how to use a debugger. But that's a too broad topic to cover here. (I really recommend it though)
The next best way is a simple printout.
for(i=strlen(m)-1;i>=0;i--)
{
printf("i: %d\n*p: %s\n*q: %s\n\n", i, p, q);
*q++=*(p+i);
*q=0;
}
It's a bit ambiguous if you want to print the string that starts at the pointers or the character. If you want the latter, change to this:
printf("i: %d\n*p: %c\n*q: %c\n\n", i, *p, *q);
Note that I both added asterisks and changed %s
to %c
.
If it is a big project. Consider writing to stderr
instead of stdout
. Just replace printf(...
with fprintf(stderr, ...
Or consider writing to a log file or something.
Upvotes: 3
Reputation: 44274
The loop "mirrors" the original text string, i.e. appends itself in reversed ordered.
It does that by
copy the last char to the end
copy the second last char to the end
and so on.
So in the loop, the string changes like:
Mirror
i = 5
Mirrorr
i = 4
Mirrorro
i = 3
Mirrorror
i = 2
Mirrorrorr
i = 1
Mirrorrorri
i = 0
MirrorrorriM
BTW:
This line:
printf("The value of s is: %c\n", &p);
is wrong. It tries to print a pointer using %c
which is undefined behavior.
Did you want:
printf("The value of s is: %p\n", (void*)&p);
Upvotes: 2