I am trying to implement a code that uses a function called reverse that takes a string and returns a new string that is the reverse of the old string. so far as I can tell the function itself works properly - i.e. I tested to see if the the reversed string: new string had the correct values and it did. However when I try to print this reversed string after it has been returned to the main function I get a bad access code. Does anyone have any ideas? Here is my code:
#include <stdio.h>
#include <string.h>
char reverse( char *string) {
char newstring[50]; //reversed string to be returned to the main function
int size = strlen(string);
int index = 0;
for (index = 0 ; index < size ; index++) {
newstring[index] = *(string+size-index-1); //creates a new string that is the reverse of the old string
}
return newstring; //reurns the new string
}
int main(int argc, const char * argv[]) {
char string[50];
printf("Please enter a string you wish to reverse:\n");
scanf("%49s", string); // user enters a string of maximum length 50
int size = strlen(string);
char *reverse_string;
reverse_string = reverse(string); // sets a pointer called reverse_string to the pointer returned by the reverse function
for ( int index = 0 ; index < size ; index++) {
printf("%c", *(reverse_string+index));// prints the reversed string value by value
}
return 0;
}
newstringis a problem asnewstringis a local variable.