Reputation: 899
#include <stdio.h>
#include <string.h>
void reverse(char * str[]) {
int i;
int reverse = sizeof(str);
for(i=0;i<=sizeof(str);i++){
*str[i]=*str[reverse];
reverse--;
}
}
main() {
char *word;
printf("Enter a word please=>");
scanf("%s",word);
reverse(word);
printf("%s",word);
}
I am trying to get a string input and pass it to reverse()
function to reverse the word entered i.e ("abcd" -> "dcba")
, however i am having some difficulty using pointers.
I am not able to change the values held by the char *word
in the memory.
Upvotes: 0
Views: 101
Reputation: 42175
You haven't allocated any storage for word
. Change
char *word;
scanf("%s",word);
to
char word[20];
scanf("%19s",word);
There are also a number of issues with reverse
strlen
to calculate the length of a string. sizeof
tells you the size of a char**
on your platform.The following (untested) function should be closer to what you want
void reverse(char* str) {
int i;
int len = strlen(str);
for (int i=0; i<len/2; i++) {
char tmp = str[i];
str[i] = str[len-i-1];
str[len-i-1] = tmp;
}
}
Upvotes: 3