-1

Possible Duplicate:
Getting Segmentation Fault

// reverse a string

#include`<stdlib.h>`
#include`<stdio.h>`
#include`<string.h>`
#include`<math.h>`
int main()
{

    char *string = "mohit",t;
    int  i=0,j; 
    printf(" %d %d",strlen(string), (strlen(string)/2)+1);
    for(i=0,j=(strlen(string)) ; i<(strlen(string)/2)+1 ; i++,j--)
    {
    printf("\n%d",(int) string);
    printf("\n%d",(int) string+5);
    printf("\ni string = %c", *(string + i));
    printf("\nj string = %c", *(string + j));
    t=*(string+i);
    *(string+i) = *(string + j);
    *(string + j) = t;  
    }
    printf("\n = %s", string);  
    return 0;
}
Community
  • 1
  • 1
r e b e l
  • 23
  • 1
  • 1
  • 5

1 Answers1

1

String literals are possibly located in a read-only area of memory; it is not allowed to assign a pointer to one to a pointer to non-const char, and thus your manipulations of string cause undefined behaviour. You either say

const char * string = "mohit";

and don't modify the string, or you create an automatic array of chars that you can modify:

char string[] = "mohit";

The latter is what you need in your case.

Also, as a point of style, writing char * s, t; in one line is possibly misleading; it is equivalent to, and should always be replaced by, char * s; char t;.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • and if i do like char string[] = "mohit"; char *p = string; is it fine according to you? – r e b e l Aug 15 '11 at 10:54
  • Yes, `string` can be a pointer to a non-constant char, because it's an automatic array. It's the same as `char string[6] = { 'm', 'o', ..., 't', 0 };`. – Kerrek SB Aug 15 '11 at 10:55