1

I've got this function below that takes a string and reverses it in C, but only using pointers. However, for some reason, I get this error every single time. This code is almost copy and paste from a source after I tried to figure out what's wrong with it, yet it still isn't working. It breaks at the *end = *ptr, any ideas? I'm lost.

char* reverseOneString(char s[STRING_LENGTH])
{
   s = "Testing";
   char temp;                  
   char* ptr = &s[0];          
   int len = strlen(s);
   
   char* end = &s[0];
   for (int i = 0; i < len - 1; i++) {
       end++;
   }
   printf("%c, %c\n", *ptr, *end);
   for (int i = 0; i < len / 2; i++) {
       printf("Schwop");
       temp = *end;
       *end = *ptr;
       *ptr = temp;
       printf("%c", *end);

       ptr++;
       end--;
   }
   
   
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Jiffypop
  • 11
  • 2

1 Answers1

0

You may not change a string literal. Any attempt to change a string literal results in undefined behavior.

Pay attention to that this function declaration

char* reverseOneString(char s[STRING_LENGTH])

is equivalent to

char* reverseOneString(char *s )

that is the element STRING_LENGTH is redundant and in fact does not make a sense. The function should work with strings of any size.

Also your function returns nothing though its return type is not void,

And if the assignment is to write the function using pointers then these for loops

for (int i = 0; i < len - 1; i++) {

for (int i = 0; i < len / 2; i++) {

should be rewritten using indeed pointers.

In any case the first for loop is redundant

int len = strlen(s);

char* end = &s[0];
for (int i = 0; i < len - 1; i++) {
    end++;
}

because you can find the last pointer using the pointer arithmetic like for example

if ( len != 0 ) end = s + len - 1;

If you want to test your function then just pass a character array that contains the string "Testing". For example

char s[] = "Testing";
reverseOneString( s );

Without using standard string functions your function can be defined the following way

char * reverseOneString( char *s )
{
    char *first = s, *last = s;

    while ( *last ) ++last;

    if ( first != last )
    {
        for ( ; first < --last; ++first )
        {
            char c = *first;
            *first = *last;
            *last = c;
        }
    }

    return s;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335