1
char str[vector_total(&final_clause)];
    for(int i = 0; i<vector_total(&final_clause); i++)
    {
          printf("%s  ", (char*) vector_get(&final_clause,i)); // outputs b  a  -c  a  a  -c  -c
          strcpy(str, (char*) vector_get(&final_clause,i));
    } 
    printf("%s", str); //only prints -c (last )
    remove_repeatation(str); // removes repeats. Expected: b a-c

Evidently its replacing 'str' everyloop. So what is the best way to fix this? Not sure if this is a easy question but I just haven't been able to crack it using different approaches.

2 Answers2

0

char str[vector_total(&final_clause)]; too small.

size_t len = vector_total(&final_clause);
char str[len*2 + 1]; // might be enough

//only prints -c (last )

Code copies vector_get() into the same location so this is expected.

Perhaps use strcat() and str[0] = 0; for the first strcat(str, .. to work.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • Thanks a bunch worked nicely. I wasn't sure at first what `str[0] = 0` did but it seemed to clean up some random characters at the beginning. – thome.steve May 02 '20 at 13:36
  • @thome.steve The first time `strcat(str, ...)` is called, `str` needs to be an empty string. That is accomplished with `str[0] = 0;`. – chux - Reinstate Monica May 02 '20 at 13:40
0

You need to use strcat instead of strcpy. strcpy replace the content of str by the result of vector_get() when strcat concatenate str and vector_get().

This should fix your problem:

char str[vector_total(&final_clause)];
char *result = NULL;
str[vector_total(&final_clause)] = '\0;
    for(int i = 0; i<vector_total(&final_clause); i++)
    {
          printf("%s  ", (char*) vector_get(&final_clause,i)); // outputs b  a  -c  a  a  -c  -c
          result = realloc(result, (sizeof(char) * strlen(vector_get(&final_clause,i));
          result = strcat(result, (char*) vector_get(&final_clause,i));
    } 
    printf("%s", str);
    remove_repeatation(str); 
twingoof
  • 9
  • 1
  • 4
  • Need `char *result == NULL;` for later `realloc()` to work. `realloc()` does not allocate for a null character - 1 too small. First `strcat(str, ...` is a problem as `str` is not a _string_. (no \0). Allocation lost with `result = strcat...` – chux - Reinstate Monica May 02 '20 at 12:06
  • Hi, thanks for the help. The first version seemed to okay and worked perfect with some of the adjustments chux - Reinstate Monica mentioned.`str[vector_total(&final_clause)] = NULL;`, I'm not sure about this lines function. – thome.steve May 02 '20 at 13:33
  • @thome.steve I ma de an error while typing this line, it's normally a '\0' to indicate the end of the string. – twingoof May 02 '20 at 16:42