7
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    //char s[6] = {'h','e','l','l','o','\0'};
    char *s = "hello";       
    int i=0,m;
    char temp;

    int n = strlen(s);
    //s[n] = '\0';
    while (i<(n/2))
    {
         temp = *(s+i);       //uses the null character as the temporary storage.
         *(s+i) = *(s+n-i-1);
         *(s+n-i-1) = temp;
         i++;
    }
    printf("rev string = %s\n",s);
    system("PAUSE");
    return 0;
}

On the compilation the error is segmentation fault (access violation). Please tell what is the difference between the two definitions:

char s[6] = {'h','e','l','l','o','\0'};
char *s = "hello"; 
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Surya
  • 147
  • 1
  • 2
  • 7

4 Answers4

16

Your code attempts to modify a string literal which is not allowed in C or C++ If you change:

char *s = "hello"; 

to:

char s[] = "hello"; 

then you are modifying the contents of the array, into which the literal has been copied (equivalent to initialising the array with individual characters), which is OK.

5

If you do char s[6] = {'h','e','l','l','o','\0'}; you put 6 chars into an array on the stack. When you do char *s = "hello"; there's only a pointer on the stack and the memory that it points to may be read only. Writing to that memory causes undefined behavior.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
0

You can try this:

void strrev(char *in, char *out, int len){
    int i;

    for(i = 0; i < len; i++){
        out[len - i - 1] = in[i];
    }
}

Note that it doesn't deal with the string terminator.

Frederico Schardong
  • 1,946
  • 6
  • 38
  • 62
0

With some versions of gcc you can allow modification of static strings with -fwritable-strings. Not that there is really any good excuse to do that.

Krunch
  • 1