In my early days of learning C on the Microware OS-9 C compiler running on a Radio Shack Color Computer, I learned about buffers.
char buffer[80];
I recall writing a “line input” routine back then which was based on one I had written in BASIC and then later BASIC09 (for OS-9).
Thirty-plus years later, I find I still end up creating that code again for various projects. Here is a line input routine I wrote for an Arduino project some years ago:
LEDSign/LineInput.ino at master ยท allenhuffman/LEDSign (github.com)
Or this version, ported to run on a PIC24 using the CCS compiler:
https://www.ccsinfo.com/forum/viewtopic.php?t=58430
That routine looks like this:
byte lineInput(char *buffer, size_t bufsize);
In my code, I could have an input buffer, and call that function to let the user type stuff in to it:
char buffer[80];
len = lineInput (buffer, 80); // 80 is max buffer size
Though, when I first learned this, I was always passing in the address of the buffer, like this:
len = lineInput (&buffer, 80); // 80 is max buffer size
Both work and produce the same memory location. Meanwhile, for other variable types, it is quite different:
int x;
function (x);
function (&x);
I think this may be why one of my former employers had a coding standard that specified passing buffers like this:
len = lineInput (&buffer[0], 80); // 80 is max buffer size
By writing it out as “&buffer[0]” you can read it as “the address of the first byte in this buffer. And that does seem much more clear than “buffer” of “&buffer”. Without more context, these don’t tell you what you need to know:
process (&in);
process (in);
Without looking up what “in” is, we might assume it is some numeric type. The first version passes the address in, so it can be modified, while the second version passes the value in, so if it is modified by the function, it won’t affect the variable outside of that function.
But had I seen…
process (&in[0]);
…I would immediately think that “in” is some kind of array of objects – char? int? floats? – and whatever they were, the function was getting the address of where that array was located in memory.
So thank you, C, for giving us multiple ways to do the same thing — and requiring programmers to know that these are all the same:
#include <stdio.h>
void showAddress (void *ptr)
{
printf ("ptr = %p\n", ptr);
}
int main()
{
char buffer[80];
showAddress (buffer);
showAddress (&buffer);
showAddress (&buffer[0]);
return 0;
}
How do you handle buffers? What is your favorite?
Comments welcome…
Famtastic C buffers and where to fimd them
:D
I knew someone would C where I was going with that.