views:

214

answers:

2

An array of pointers to strings is provided as the input. The task is to reverse each string stored in the input array of pointers. I've made a function called reverseString() which reverses the string passed to it. This functions works correctly as far as i know.

The strings stored/referenced in the input array of pointers are sent one by one to the reverseString() function. But the code hangs at some point in the reverseString() function when the values of the passed string are swapped using a temp variable. I can't figure out why the code is hanging while swapping values. Please help me with this.

The code is as follows:

#include <stdio.h>
void reverseString(char*);

int main()
{   char *s[] = {"abcde", "12345", "65gb"};
    int i=0;
    for(i=0; i< (sizeof(s)/sizeof(s[0]) ); i++ )
    { reverseString(s[i]);
     printf("\n%s\n", s[i]);
    }

    getch();
    return 0;
}//end main

void reverseString(char *x)
{   int len = strlen(x)-1;
    int i=0; 
    char temp;
    while(i <= len-i)
    { temp = x[i];
     x[i] = x[len-i];
     x[len-i] = temp;
            i++;
    }
}//end reverseString
+2  A: 

The strings ("abcde" etc) could be stored in readonly memory. Anything is possible when you try to modify those strings, therefore. The pointers to the strings are modifiable; it is just the strings themselves that are not.

You should include <string.h> to obtain the declaration of strlen(3), and another header to obtain the function getch() - it is not in <stdio.h> on my MacOS X system (so I deleted the call; it is probably declared in either <stdio.h> or <conio.h> on Windows).

Jonathan Leffler
`getch()` is in `<conio.h>`; it is of course non-standard (I think, originating from Turbo C).
Pavel Minaev
Thanks Pavel; I'll try to remember that.
Jonathan Leffler
+6  A: 

You are trying to change string literals.

String literals are usually not modifiable, and really should be declared as const.

const char *s[] = {"abcde", "12345", "65gb"};
/* pointers to string literals */

If you want to make an array of modifiable strings, try this:

char s[][24] = {"abcde", "12345", "65gb"};
/* non-readonly array initialized from string literals */

The compiler will automatically determine you need 3 strings, but it can't determine how long each needs to be. I've made them 24 bytes long.

pmg
To clarify: in the first example (and code in the question), you have pointers to string literals (which are read-only). In the second example, you have a non-readonly array initialized _from_ string literals.
Pavel Minaev
Thank you @Pavel. Hope you don't mind that I copy your comment to my answer.
pmg
gjhf