I wrote the following function for removing duplicate characters from a string..For ex: if str = "heeello; removeDuplicate(str)
will return helo...But it shows some error on runtime .I have added some printf() statements for debugging...Can anyone tell me what the problem is ?
char* removeDuplicate(char str[])//remove duplicate characters from a string,so that each character in a string is not repeating { int i = 0,j; char ch; printf("\nstr is %s",str); while((ch = str[i++] )!= '\0') { j = i; printf("\n----ch = %c----",ch); while(str[j] != '\0') { printf("\n--------Checking whether %c = %c \n",str[j],ch); if(ch == str[j]) { printf("\n------------Yes"); while(str[j]!='\0') { printf("\nRemoving %c %d -- \n",str[j]); str[j] = str[++j]; --i; } break; } printf("\n------------No"); //printf("\njj"); j++; } } return str; }
\0"heee" is just like {'h', 'e', 'e', 'e', '\0'}str[j] = str[++j];. The C specification doesn't specify how the compiler should behave in this case (see c-faq.com/expr/evalorder1.html). Also doingi--is not a very wise thing to do in such constructions. In this caseiwill become negative in a lot of cases, andstr[-1]is clearly not valid here.