1

Following is the C code I tried for removing duplicate character in a string, but it is not running properly, it get stuck at comment stuck. Please help me to understand what I am doing wrong?

void removeDupliacte(char *str)
{
    int bitset=0;
    int value= 0;
    char *tail = str;
    char temp;
    int i=0;
    while(*str)
    {
        value = *str - 'a';
        if(bitset & (1 << value) > 0 )
        {
            str++;
        }
        else
        {
            bitset |= 1 << value;
            temp = *str;
            tail[i] =temp; /*stuck*/
            i++;
            str++;
        }
    }
tail[i++] = '\0';

}

int main()
{
    char *str = "abac";
    removeDupliacte(str);
    printf("%s",str);
    return 0;
}
MByD
  • 135,866
  • 28
  • 264
  • 277
Ankur
  • 788
  • 6
  • 13
  • This: `if(bitset & (1< 0 )` in your while loop cannot be right. It will always evaluate to 0, i.e. `false`. I'll have a look at the rest, but there is definitely something wrong there. Also, the parens are not balanced. – Joel Lee Apr 16 '11 at 08:36
  • I'm thinking its probably supposed to be if( (bitset & (1 << value)) > 0 ) due to > having a higher precedence than &. – Stephen Brown Apr 16 '11 at 08:59

2 Answers2

2

str is a const string, meaning stored in an area that you cannot modify (char *str = "abac";) tail points to str and you cannot edit it as well, tail[i] =temp; is an attempt to write to read only area.

One solution is to change the declaration of str to char str[] = "abac"; which will allocate an array in the size of "abac\0" and copy the string "abac\0" to it. Since arrays are in a read-write memory (in case of array in a function - on the stack) you will be able to modify the string. As appose to char *str = "abac"; which puts the string in read only memory and assign the pointer to the string to str.

MByD
  • 135,866
  • 28
  • 264
  • 277
  • Because you "tell" the compiler - put the string "abac" in data segment and give me its address. Data segment is read only. See this answer as well: http://stackoverflow.com/questions/2241834/why-is-my-char-writable-and-sometimes-read-only-in-c – MByD Apr 16 '11 at 19:41
1

Additionally, you should try changing your if statement to:

if( (bitset & (1 << value)) > 0 )

Otherwise it's not doing what it's supposed to be doing due to the operator precedence.

Stephen Brown
  • 315
  • 2
  • 9