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;
}
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
.
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.
精彩评论