r/C_Programming • u/Icefrisbee • 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
4
u/[deleted] Jul 12 '26
The expression
*buffer + iis parsed as(*buffer) + i, not*(buffer+i), so the for loop is never actually accessing beyond the first element ofbuffer. The subsequent characters it prints are from addingito the first character's ASCII value. Try inputting the string "az", and you will see it still printsabcde.17
u/aocregacc Jul 12 '26
*buffer + iis not the same as*(buffer + i)1
u/Icefrisbee Jul 12 '26
Also for some reason my formatting for this post isn’t working, if anyone knows why please let me know
4
u/rampallianuraag Jul 12 '26
That's because you're basically printing (*buffer)+i. So first (*buffer) is always a. The loop runs from 0 to 4 so first you're printing a+0 which is a,a+1 which is b,a+2 which is c,a+3 which is d, finally a+4 which is e. Because of which the null character is never printed, even if you print the null character it's not visible.
3
u/TrondEndrestol Jul 12 '26 edited Jul 12 '26
You better check the return value of
fgets, you will get a null pointer on failure.The size of the array and the second parameter of
fgetsshould take both a new line character and the null terminator into account. In other words,n + 2for the size of the array, andn + 1for the second parameter offgets.Either start and end your code with triple back ticks on separate lines, or ensure a minimum of four blanks on each line of code.
1
u/East_Nefariousness75 Jul 12 '26
Your buffer is 3 bytes long but you read 5 bytes in the loop.
Additionally, fgets will read at most n - 1 byte to leave space for the null terminator. So if you write ABCD, only A and B will end up in the buffer.
The character zero(0) is not represented by the 0 byte.
1
u/burlingk Jul 12 '26
It is also worth noting that you are suggesting a 3 character buffer, and asking for 5 in your output loop. That is undefined behavior. There is no way to guarantee what will exist in the last three positions you are trying to look at.
And, you are also providing a buffer for 3 characters, and feeding it 4, and then questioning why the 5th one is weird.
buffer was defined as char[3]. So your last statement:
printf(“%s”, buffer)Was the only one that actually acted in a 'normal' way. "ab" is a string literal that takes up three characters worth of space.
{a, b, \0}And that is what is in buffer. 'cde' was a boundary error, and undefined. There is no guarantee that every implementation would have even accepted that part to begin with.
Edit: Another tip for posting code is that there are pastebin sites that handle code formatting well. You can paste your code to one of those and then paste a link. :)
1
u/kazah-png Jul 13 '26
El problema de raíz está en esa línea que tienes en el
printfdentro del bucle. Ojo, que*buffer + iNO es lo mismo quebuffer[i].*bufferlo que hace es agarrar el valor de la primera posición de tu array, o sea la'a'. Como en C uncharen realidad es un número (el código ASCII), al hacer*buffer + ilo que estás haciendo es sumarle 1, 2, 3 y 4 al número de la'a'. Por eso te imprimea, 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 puestobuffer[i]ahí, entonces sí estarías recorriendo el array.Y sobre el famoso
NULLo\0, ese está guardado enbuffer[2], pero como tu bucle nunca llega abuffer[2](porque estás usando la otra fórmula), pues nunca te lo encuentra. Y aunque llegara, si usas%cno te va a pintar un0en 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
fgetssolo 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 otroscanfofgets, te los va a escupir sin preguntarte.