Possible Duplicate:
Why do I get a segmentation fault when writing to a string?
What is the difference between char a[] = “string”; and char *p = “string”;
I have find the fault ,but I don't know why. so would you help me ?
If I define the char str[] instead the char * str in the main function , it can work normally , else the line of *pSlow = *pFast; will crash with "Unhandled exception at 0x012314f3 in shanchu.exe: 0xC0000005: Access violation writing location 0x0123583c."
Thanks
#include <stdio.h> #include <string.h> #include <iostream> char * delChar(char *s,int iLen) { if((s == NULL) || iLen <= 0) { return NULL; } int i; const int MAXLEN = 26; unsigned int min,hashTable[MAXLEN]; for(i = 0;i < MAXLEN;i ++) { hashTable[i] = 0; } for(i = 0;i < iLen;i ++) { hashTable[*(s + i) - 'a'] ++; } while(hashTable[i] == 0) { i ++; } min = hashTable[i]; for(i = 0;i < MAXLEN;i ++) { if(hashTable[i] != 0) { if(hashTable[i] < min) { min = hashTable[i]; } } } char *pSlow = s; char *pFast = s; while(*pFast != '\0') { if(hashTable[*pFast - 'a'] != min) { *pSlow = *pFast; pSlow ++; } pFast ++; } *pSlow = '\0'; return s; } int main() { char* str = "abadccdehigiktk"; int iLen = strlen(str)/sizeof(char); char *tmp = delChar(str,iLen); printf("%s\n",tmp); system("pause"); }