What you actually mean with "buffer" is what we and the C standard calls an "array".
An array is a sequence or collection of several objects of the same type, stored contiguous in memory, as opposed to a structure, which can hold objects of different types.
Quote from the yet-current C standard ISO/IEC 9899:2018 (C18), 6.2.5/20:
"An array type describes a contiguously allocated nonempty set of objects with a particular member object type, called the element type. The element type shall be complete whenever the array type is specified. Array types are characterized by their element type and by the number of elements in the array. An array type is said to be derived from its element type, and if its element type is T, the array type is sometimes called "array of T". The construction of an array type from an element type is called "array type derivation"."
The term "buffer" is more used to describe a temporary storage, but an array is in most cases, in this explicit comparison, more "static"-like although you can create dynamic and variable-length arrays, too. Note that this "static" is not to be confused with the static
keyword but the explanation and the use of that is far away from now.
Also a "buffer" might be just one single object of a certain type; it does not need to be an array of objects.
Quote from the Stack Overflow "buffer" tag wiki:
"A buffer is an area of memory set aside for temporary storage of data while it is being moved from one place to another. This is typically done to speed up processes with significant latency, such as writing to a disk, printer or other physical device. The output is ready to be sent to the device before the device is ready to accept it, so it is moved to the buffer so that the sending program does not have to continue waiting."
We can define an array by specify the amount of single objects to hold. This is made by the number inside []
.
So,
char buffer[1024];
means buffer
is an array with the identifier or name "buffer"
which holds 1024 char
objects.
You can omit the number of elements, if you initialize the array directly by its definition with appropriate values. The compiler will detect the amount of elements automatically and adjusts the size of the array accordingly.
int buffer[] = {1,2,3,4,5}; // That is permissible.
int buffer[]; // That is not permissible.
The []
always indicates either an array itself or a pointer to an array, when used f.e. as a parameter of a function:
void foo(char array_pointer[])
In this case array_pointer
is not an array itself, but a pointer to an array of char
in the calling function.
You should note, that index counting starts at 0
when you later want to access a certain object in the collection.
This means if you want to access the first element of buffer
, you need to use:
buffer[0]
buffer[0]
refers to the first element, buffer[1]
to the second element, buffer[2]
to the third element and so on.