TheGMX
TheGMX

Reputation: 153

Why copying a character to a char array results in weird behaviour

I have the following code which aims to implemente a simple LZW based text compression:

int compress(FILE text_file, FILE *output) {
  char input[20];
  short code = 0;
  short size = 0;

  memset(input, '\0', 20);
  
  char c = fgetc(text_file);
  while (c != EOF) {
    strncat(input, &c, 1);
    code = getCodeFromInput(input);
    if ((size + 1) > 1 && code == -1) {
      addInput(input);
      fwrite(&code, 2, 1, output);
      strcpy(input, &c);
      printf(%s, input);
      size = 1;
      code = 0;
    } else {
      size++;
    }
    c = fgetc(text_file);
  }
  fwrite(&input, 2, 1, output);
  return 0;
 }

So after finding a suitable string I need to override my string input with with the last char I've received. When using strcpy() I can easily copy arrays to my input string, but when trying to copy a single character, if I print the result I will get the expected output plus some weird character, for example copying the caracter 'a' I get a�. Is this expected? Why does strcpy() behave like that?

Upvotes: 1

Views: 144

Answers (1)

David Ranieri
David Ranieri

Reputation: 41065

The standard defines strcpy as a function copying a NUL terminated string, you are copying the last input (a character), but even if you get his address, it is not a NUL terminated string:

strcpy(input, &c);

you can try using a compound literal:

strcpy(input, (char[2]){c, '\0'}); // A NUL terminated string

Also, notice that fgetc wants an int instead of a char in order to handle EOF:

char c = fgetc(text_file);

should be

int c = fgetc(text_file);

in consequence:

strcpy(input, (char[2]){(char)c, '\0'}); // A NUL terminated string

Upvotes: 2

Related Questions