0

I am VERY new to C programming. I have a function which will take a pointer to a string as input and print the reverse of that string. When I invoke that function in the main method, it outputs junk. I think it might be a problem with how I am using pointers.

My code is:

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

    #define MAX_LEN 100

    void reverse(char* str)
    {
        int i, j;
        int temp;
        int length;
        length = strlen(str);
        i= 0;
        j=(length-1);
        while (i<j){
          temp=str[i];
          str[i] = str[j];
          str[j]=temp;
          i++;
          j--;
       }
        printf("Your reversed string is: ");
        for (i=0; i<length; i++){
          printf("%d", str[i]);
       }
       printf("\n");
    }

int main()
    {
        char mystring[MAX_LEN+1];
        printf("Enter the string. \n");
        scanf("%s", mystring);
        printf("%s", mystring);
        printf("\n");
       reverse(mystring);
    }

and the output is:

Enter the string.
help
help
Your reversed string is: 112108101104

1 Answer 1

4

printf("%c", str[i]); You printed the ascii values earlier. Use %c specifier to print the characters.

For example, you can see that in ascii-chart

112 108 101 104
 p   l   e    h

Or even more easily you could have done this

printf("%s",str);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.