user1149549
user1149549

Reputation:

Issues with reversing a string in place

I am writing a code to reverse a string in place:

void ReverseInPlace(char * x)
{
    char * end = x;
    int i;
    i = 0;
    char temp;
    while(*end)
    {
        ++end;//point tol end 
        ++i;//count the lenght
    }
    --end;
    printf("%s",end);

    printf("%d",i);
    while(i)
    {
        temp = *end;
        printf("%s","\n");
        printf("%c",temp);

        end--;
        x++;
        i--;
    }
    printf("%s","\n");//blank line
    printf("%s","\n");//blank line
    printf("%s","-----");//blank line
    printf("%s",x);//print original 
}

Here are my confusions:
Even though I am able to print the characters in reverse, I want to reverse the string without using an array

I get error when I try to do the following:

*x = temp;

Upvotes: 0

Views: 217

Answers (3)

hanish
hanish

Reputation: 67

char *p="abcd123"; // ........string literal stored in read only memory mostly in text segment(where the code is stored) so you should never change value here as it may crash your program by writing onto code. Here p is pointing to address which maybe in text segment.

char q[]="abcd1234"; //..... the values can be changed and array size can be modified but address cant be changed because the array is nothing but a constant pointer. That's the problem with your code .....you are calling the function and parameter is a string literal whereas it should be a constant pointer. Further the storage class here is stack so u can modify the values.

Upvotes: 0

dnsmkl
dnsmkl

Reputation: 792

My proposal

#include <stdio.h> // printf
#include <string.h> // strlen

void swap(char* a , char* b)
{
    char tmp;
    tmp=*a;
    (*a) = (*b);
    (*b) = tmp;
}

void ReverseInPlace(char * x)
{
    char * end = x;
    int i,j,length;
    char temp;

    length = strlen(x);

    //swap 1st with last, then 2nd with last-1, etc.  Till we reach the middle of the string.
    for(i=0,j=length-1 ; i<j ; ++i,--j)
        swap( &x[i] , &x[j]);
}

main (){
    char str[] = "123456789";
    ReverseInPlace(str);
    //ReverseInPlace("1234"); // this would lead to error, because "1234", can not be modified
    printf("%s\n",str);
}

After middle is reached, you would swap elements which were already swapped by previous iterations. For illustration:

char* x = "1234";
1 2 3 4
4 2 3 1
4 3 2 1 // already reversed!
4 2 3 1
1 2 3 4 // if we continue till i==length-1 && j=0 , then we just get where we started

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249133

You say you are doing this:

ReverseInPlace("123456789");

You need to do something like this:

char str[] = "123456789";
ReverseInPlace(str);

Doing it the latter way allocates storage which you can modify, as opposed to modifying a literal string, which is illegal.

Upvotes: 2

Related Questions