Pointer positioning

Asked

Viewed 45 times

0

I wrote this code to make switch between the letters of a string, but it doesn’t even print anything, someone can explain to me why?

Code:

#include <stdio.h>
#include <string.h>

int main()
{
        char *p, *p1, p2;
        char str[10];
        fgets (str, 10, stdin);
        p=str;
        p1=str;
        while (*p1 != '\0')
        {
                p1++;
        }
        while (p!=p1)
        {
                p2=*p;
                *p=*p1;
                *p1=p2;
                p++;
                p1--;
        }
        printf ("\n%s", str);
        return 0;
}
  • 1

    your code is very confusing...put comments in the code explaining what you are trying to do

3 answers

1

In the second cycle while the first exchange puts '\0' at the first position of the string, effectively leaving the empty string.

Assuming the user input "foo".

Just before the while cycle the situation is:

| f | o | o | \0 |
  ^ p         ^ p1

In the execution of the loop, the '\0' is exchanged with the 'f' and the updated pointers.

| \0 | o | o | f |
       ^ p ^ p1

1

#include <stdio.h>
#include <string.h>

int main()
 {
char *p, *p1, p2;
char str[10];
fgets (str, 10, stdin);
p=str;
p1=str;
while (*p1 != '\0')
{
    p1++;
}
while (p < p1)
{
    p2=*p;
    *p=*p1;
    *p1=p2;
    p++;
    p1--;
}
printf ("\n%s", p1);
return 0;
}

Only exchanges the condition within the second while, and in the printf exchanges str by P1 ;)

-1

You’re doing the var print str but that var has no value at all so you’re printing a whitespace.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.