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