0

I am not allowed to use any headers, and I want to create code, that takes a string input and modifies it to its reverse. There are no compile-time errors, however during run-time it does change the string to empty, rather than reverse.

int str_size(char str[])
{
    int i=0;
    while (str[i]!='\0')i++;
    return i;
}

void str_rev(char str[])
{
    char buff;
    int size=str_size(str);

    if(size==0 || size==1){}
    else
    {
        for (int i = 0; i < (size/2)-1; i++)
            {
                buff=str[i]; 
                str[i]=str[size-i];
                str[size-i]=buff;
            }
    }
}

str_rev is called in main(void).

The terminal message:

iplayzed@iplayzed-Lenovo-ideapad-330-15IKB:~/Egyetem/Progalap gyak 1.fv/3_hazi$ gcc -Wall -O2 -static -o my my.c
my.c: In function ‘main’:
my.c:30:5: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result [-Wunused-result]
     scanf("%s",str);
     ^~~~~~~~~~~~~~~
iplayzed@iplayzed-Lenovo-ideapad-330-15IKB:~/Egyetem/Progalap gyak 1.fv/3_hazi$ ./my
asdf
String length: 4

The original string:"asdf"
The reversed string:""

What is the cause of it changing to blank?

1 Answer 1

2

The indices for the reversal are a little off by 1.

Consider size=4, then for the first iteration (i=0), code will execute:

  1. buff = str[0]
  2. str[0] = str[4-0] ;
  3. str[4] = buff ;

Recall that str[4] is the terminating NUL, so that the code will insert NUL into the first position, therefore an empty string is returned.

This can be easily fixed by:

buff=str[i]; 
str[i]=str[size-i-1];
str[size-i-1]=buff;
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, there was "empty string" because the NUL terminator was being copied to the front of the string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.