tags:

views:

139

answers:

3
+5  Q: 

reverse a string

#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 defination char s[6] = {'h','e','l','l','o','\0'}; char *s = "hello";

+10  A: 

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.

anon
+4  A: 

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
A: 

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