Reputation: 101
I am trying to delete all duplicate characters from a given string. For example "asdasd" = "asd" or "abbgga" = "abg".
When I compile and when cmd starts to run it I am getting "stopped working" message.
This is my code :
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void delMul(char str[]){
int i,j=0;
int s[26];
char k ;
for ( i = 0; i < 26; i++)
{
s[i] = 0;
}
for (i = 0; i < strlen(str); i++)
{
k = str[i] - 'a';
if(s[k] == 0) {
s[k]++ ;
str[j++] = str[i];
}
}
str[j] = '\0';
}
int main(){
char *str = "asdasd";
delMul(str);
puts(str);
}
Upvotes: 0
Views: 62
Reputation: 34357
In main you have declared str as a pointer to a string
So the storage is allocated as a fixed string in the program and not as data
So when you attempt to write to it at line 18 str[j++]=str[i]
there is a
SEGV as this is not allowed
To correct this declare the string as an array of char that is initialized instead
int main(){
char str[] = "asdasd";
delMul(str);
puts(str);
}
Upvotes: 1
Reputation: 134336
In your code, str
points to a string literal, which might not be modified. Try using an array for the same initialized by the string.
Upvotes: 2