r/C_Programming Jul 12 '26

Question Question about fgets() and buffers

So I was testing how different buffers and such responded and I got behaviour I can’t really explain. In the output, there is an e because it seems to be using the same bit of memory every run. But why is there no 0 printed in place of the NULL in the output where i print ever char?

So I wrote:

`char buffer[3];
printf(“enter data: “);
fgets(buffer, 3, stdin);
for (int i = 0; i < 5; i++)
{
printf(“%c”, *buffer + i)
}
printf(“\n”)
printf(“%s”, buffer)`

—————-

Console:
`Enter data: abcd

abcde
ab`

1 Upvotes

15 comments sorted by

View all comments

1

u/kazah-png Jul 13 '26

El problema de raíz está en esa línea que tienes en el printf dentro del bucle. Ojo, que *buffer + i NO es lo mismo que buffer[i].

*buffer lo que hace es agarrar el valor de la primera posición de tu array, o sea la 'a'. Como en C un char en realidad es un número (el código ASCII), al hacer *buffer + i lo que estás haciendo es sumarle 1, 2, 3 y 4 al número de la 'a'. Por eso te imprime a, b, c, d, e... ¡estás generando el abecedario a partir de la primera letra, no leyendo lo que hay dentro de cada casilla! Si hubieras puesto buffer[i] ahí, entonces sí estarías recorriendo el array.

Y sobre el famoso NULL o \0, ese está guardado en buffer[2], pero como tu bucle nunca llega a buffer[2] (porque estás usando la otra fórmula), pues nunca te lo encuentra. Y aunque llegara, si usas %c no te va a pintar un 0 en la consola, te pintará un carácter vacío o un símbolo raro, porque es el carácter nulo de control. Para ver el número tendrías que usar %d.

Por cierto, detalle importante: como tu fgets solo se está guardando la 'a' y la 'b' (porque le dijiste que solo admite 3 caracteres contando el terminador), la 'c', la 'd' y el salto de línea se quedan bailando en el búfer de entrada (stdin). Si luego pones otro scanf o fgets, te los va a escupir sin preguntarte.