-3

I'm trying to reverse a string without using a temp string, but when I execute the program I have olllo as result not olleH.

Here is my code:

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

    int main(){
        char *str = strdup("Hello");
        int reverse(char * str){
            int i=0;
            int j = strlen(str)-1;
            while(i<=j){
                (str[i]) = (str[j]);
                i++;
                j--;
            }
        return 0;
        } 
        reverse(str);
        printf("string = %s\n", str);
        return 0; 
    }
kenorb
  • 155,785
  • 88
  • 678
  • 743
James H
  • 187
  • 1
  • 1
  • 6
  • This is not C. You cannot nest function definitions in C. –  Nov 02 '14 at 15:04
  • 1
    @rightføld: He may be using gcc's extension which allow it. – Jack Nov 02 '14 at 15:07
  • It's not dupulicated, i'm trying to create a function that reverses a string without using a temp string. I didn't find an exemple like this – James H Nov 02 '14 at 15:14

1 Answers1

1

You cannot do such thing since your char *str is a kind of constant variable : you've just put something in it without using any dynamic memory allocation function like malloc(). You cannot modify this pointer's content unless you duplicate it.

Use strdup(char *) like this :

char * str = strdup("Hello");

Then you'll be able to modify your strings content.

Amina
  • 404
  • 4
  • 14
  • I've tried this but i have olllo as result and not olleH – James H Nov 02 '14 at 15:19
  • 1
    @JamesH Now that the segmentation fault is resolved, I suggest asking a new question. – 2501 Nov 02 '14 at 15:22
  • Now the problem is in your algorithm. When you swap your characters, you never store the previous value of str[i] in a tmp_char, you just lose it. – Amina Nov 02 '14 at 15:25