char string, change;
char *ptr;
int len;
You don't use change or len, so there's no point in having them. string is wrong on many different levels, the foremost being that it can only hold one char instead of an entire string of them. The second problem is that all identifiers in C that start with "str" in lower case are reserved by the implementation for further updates. You can consider them reserved words like if and else. You also should use global variables when possible, they are considered bad programming style unless absolutely necessary.
This only takes the first character in the string. The output will probably not be what you want.
for(ptr = string; *ptr != NULL; ptr++)
{
printf(ptr, "%c", ptr);
};
First, since string is a char this assignment is broken, you're trying to assign the contents of string to a pointer. Definitely not the effect you want. I've also got bad news for you in the condition of the loop, I doubt that the user will enter a null pointer anywhere in the string, so this loop will continue for who knows how long. This can be fixed by testing for a nul character instead, something like
*ptr != '\0'
Your call to printf is also wrong, it should look like this:
printf ( "%c", ptr );
This would work much better, but according to your requirements it is still incorrect. The string is indeed printed out, but in the wrong order. You wanted it in reverse:
Code:
#include <stdio.h>
int main ( void )
{
char *ptr;
char astring[BUFSIZ];
printf("Write your string: ");
fgets ( astring, sizeof astring, stdin );
for(ptr = astring; *ptr != '\0'; ptr++)
printf("%c", *ptr);
return 0;
}
To fix this you can forget about using the pointer safely, so let's just stick with an index that starts at the end of the string and goes to 0.
Code:
#include <stdio.h>
#include <string.h>
int main ( void )
{
int ptr;
char astring[BUFSIZ];
printf("Write your string: ");
fgets ( astring, sizeof astring, stdin );
for(ptr = strlen ( astring ) - 1; ptr >= 0; ptr--)
printf("%c", astring[ptr]);
return 0;
}
-Prelude