Search code examples
cstringpointersunsigned-char

reverse a string using pointers (have to use unsigned *char) in C


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 :)


Solution

  • You are trying to modify a string constant. Replace

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

    with

    char array[] = "Hello";