c – "Garbage" values ​​in arrays?

Question:

I have been practicing how to use vectors in c, and I have come across several simple programs that I have made with "garbage" values, for example in the following code that consists of the user entering their full name, including spaces:

int main()
{
 int nombre,i=0;
 char s[20];
  printf("introdusca su nombre\n");
  while ((nombre = getchar()) != '\n')
   {
      s[i] = nombre;
      i++;
   }
  printf("%s\n", s);
}

when executing the program, if it is possible to print the name including the spaces, but the problem is that many signs are added like these ╗┐ followed by the printed name, I don't know what the problem is, like when I use arrays but instead of characters are numbers, something similar happens to me, but instead of ╗┐, I get extremely large numbers instead of the ones I type.

Answer:

In C character strings are stored with null termination . This means that a null character '\0' is placed at the end of a character string. This character acts as a marker that lets the chain handling functions know that the end of the chain has been reached. printf is one of those functions.

With the code you have written, the characters that the user presses until he presses line break are stored. But the null character terminator is never stored. That is why the printf prints what the user has written followed by the garbage that was in the array.

The solution is to save the null character after the last saved character:

int main()
{
 int nombre,i=0;
 char s[20];
  printf("introdusca su nombre\n");
  while ((nombre = getchar()) != '\n')
   {
      s[i] = nombre;
      i++;
   }
  s[i] = '\0'; // Marco el final de cadena con un caracter nulo
  printf("%s\n", s);
}

The above code has a flaw. If the user enters 20 or more characters before pressing the line break then we will write outside the array. This is a mistake but that would be a matter for another question.

Scroll to Top