0

I am currently working on an assignment for Uni.

The task is to reverse a string in a separate function. The function-name is given like that:

void string_rev(unsigned char *str);

My Solution looks like this:

void string_rev(unsigned char *str){

    int length = 0;
    int counter = 0;
    unsigned char *endptr = str;   

    for (int i = 0; str[i] != '\0'; i++)  //getting length of string
        length++;

    for (int i = 0; i < length; i++)     //putting endptr to end of string
        endptr++;

    while (counter < length/2){      //switch values from start to end until half of string
        char temp = *str;
        *str = *endptr;
        *endptr = temp;
        str++;
        endptr--;
        counter++;
    }


    for (int i = 0; i<length; i++){
        printf("%c", *str);
        str++;
    }

}


int main (void){


    char *array = "Hello";
    unsigned char *ptr = (unsigned char*)array;


    string_rev(ptr);


    return 0;

}

The Error I get is Bus Error 10! But I can't find the mistake.

It may has to do with the unsigned char* but I don't get it to work. Can someone please help?

FYI -> We have to use unsigned char*! And of course pointers!

Thank you :)

Evg
  • 25,259
  • 5
  • 41
  • 83
Easymoney_
  • 13
  • 2
  • 3
    Just an aside, you can use `strlen(str)` to get the length of a string. You don't need `for (int i = 0; str[i] != '\0'; i++) length++;`. And you can replace `for (int i = 0; i < length; i++) endptr++;` with just `endptr += length;`. Note also that your `endptr` initially points to the trailing null, so your swapping loop will need to take that into account. – lurker Jan 03 '20 at 16:53
  • Tip: Change all instances of `unsigned char` to just `char`. After all, you even use `char` inside the function! – ikegami Jan 03 '20 at 16:54
  • Tip: The second loop can be replaced with `endptr += length;` – ikegami Jan 03 '20 at 16:55
  • Tip: You don't need `counter`. Simply loop until `endptr < str`. – ikegami Jan 03 '20 at 16:56
  • Tip: The last loop can be replaced with `printf("%s\n", str);` – ikegami Jan 03 '20 at 16:59
  • Thank you! Really appreciate your tips! And it works now :D – Easymoney_ Jan 03 '20 at 19:07
  • I should have said until `endptr <= str`, which is to say while `endptr > str`. – ikegami Jan 04 '20 at 11:41

1 Answers1

5

You are trying to modify a string constant. Replace

char *array = "Hello";   // Not an array.

with

char array[] = "Hello";
ikegami
  • 367,544
  • 15
  • 269
  • 518