String reverse function Are there more optimization possible in this code to achieve better performance and minimal memory usage?

#include&lt;stdio.h&gt;
char * strrev(char* str)
{
     int length=0;
     char* str1=str;

     while(*str++)
        ++length;

     str=str1;
     char  temp;

     for ( int i=0; i&lt; length/2; ++i)
     {
           temp= *(str +i);
           *(str +i) = *(str+length -1-i);
           *(str+length -1-i)= temp;
     }

     return str1;
}
int main()
{
    char str[]="Hello World!";
    strrev(str);
    printf("Reversed str:%s", str);

    return 0;

}
Sure there is... use the native libraries...

Your code here:


 int length=0;
 char* str1=str;

 while(*str++)
    ++length;



counts the number of chars until it finds the null terminator.

This is an inefficient way of doing it, 1 byte at a time. A much more efficient way to do it is to work on word-sized memory chunks - 32-bits and 64-bits on respective platforms. If you do a fold of the 8-bit bytes using bitwise operators on the value, you can identify whether there is a null byte in fewer CPU operations than by processing each byte individually. If this sounds complicated, well, it sort of is, but, on the other hand, it is already done for you:

#include &lt;string.h&gt;

....

    length = strlen(str);


That will likely halve the time needed to find the string length.

Then, your code would be a lot easier to read if you used array-like subscripts to access the chars instead of pointers..... that way you can get rid of the str1 variable as well:

 char  temp;

 for ( int i = 0; i &lt; length/2; ++i) {
       temp = str[i];
       str[i] = str[length - 1 - i];
       str[length - 1 - i] = temp;
 }


If you want, you can reduce that to a while-loop with converging indices:

 int right = length - 1;
 int left = 0;
 while (left &lt; right) {
     temp = str[left];
     str[left++] = str[right];
     str[right--] = temp;
 }