0

I'm attempting to remove duplicate characters from a string without using any additional buffer. The code works when I declare a single variable like this

char s[] = "aaabbb";

but not when I'm attempting to loop through a few test cases.

#include <stdio.h>
#include <string.h>

/* Design an algorithm and write code to remove the duplicate characters in a string
without using any additional buffer. NOTE: One or two additional variables are fine.
An extra copy of the array is not. */

void removeDuplicates(char s[]) {
    // attempts to modify array in place without extra buffer
}

int main() {
    char *s[4] = {"aaaa", "abcd", "ababab", "aaabbb"};

    int i;
    for (i = 0; i < 6; i++) {
        removeDuplicates(s[i]);
    }
    return 0;
}

This returns Bus error: 10 because it's attempting to modify the string literal "aaaa" but I'm not sure how to overcome this while maintaining a nice setup for the test cases.

David Stevens
  • 835
  • 1
  • 6
  • 15

1 Answers1

2

The s[i] are pointing to string literals, you need a 2-dimensinal char array like this:

char s[][7] = {"aaaa", "abcd", "ababab", "aaabbb"}

Also note that for a string of length n you need at least n+1 spaces because of the '\0'-termination."aaabbb"` has length 6, so it need at least 7 spaces.

Then you can do

int main() {
    char s[][7] = {"aaaa", "abcd", "ababab", "aaabbb"};

    size_t i;
    for (i = 0; i < sizeof s / sizeof s[0]; i++) {
        removeDuplicates(s[i]);
    }
    return 0;
}
Pablo
  • 13,271
  • 4
  • 39
  • 59