I have the following code:
#include <stdio.h>
int main(void)
{
char cadena[5] = {0};
int c = 10;
printf("Escriba una cadena: ");
scanf("%s", cadena);
printf("Resultado: %s, %d", cadena, c);
return 0;
}
The problem is that when the user enters 5
or more characters, the array overflows (it exceeds the limits) and incidentally, overwrites the content of the variable c
.
Example:
If the user enters a by keyboard 12345
, the result on the screen would be:
Resultado: 12345, 0
The example shows how the variable c
loses the value it had previously. So the question is: How do I avoid this potential overflow?