which is correct:
orCode:#define SIZE 1024
.....
char buffer[SIZE];
.....
buffer[SIZE] = '\0';
.....
?Code:#define SIZE 1024
.....
char buffer[SIZE];
.....
buffer[SIZE-1] = '\0';
.....
Printable View
which is correct:
orCode:#define SIZE 1024
.....
char buffer[SIZE];
.....
buffer[SIZE] = '\0';
.....
?Code:#define SIZE 1024
.....
char buffer[SIZE];
.....
buffer[SIZE-1] = '\0';
.....
The second one.
NUMBER TWO!
Remember, the first element is zero. The first error is how we get an "off-by-one" error, closely related to the "fence post" error (believing that a 100' fence with posts spaced ten feet apart will require only ten posts).
doesn't C append the '\0' to character strings automatically?
No. The string functions in string.h will. And the definition of a C string is a null terminated character array.
But a character array such as "buffer" is not automatically a C string. If you are not using string.h functions to populate it, then you do need to add '\0' yourself.
If you are talking about string literals, then yes, a null character will be appended in order for them to meet the definition of string in C. In this case we only have an array since we do not know what happens in the code that has been left out.Quote:
Originally Posted by KBriggs
However, not all the functions declared in <string.h> (even some of those whose names start with the letters "str") actually append a null character on each invocation of the given function.Quote:
Originally Posted by MK27
Neither is particularly correct since buffer doesn't contain anything but garbage.
If you intend to use it as a C-style string and expect it to be empty then you should set the first char to 0: buffer[0] = '\0';
As a side effect of this nasty business of leaving things out of the code example... we don't actually know that either. Maybe buffer is a global variable and thus is zero initialised.Quote:
Originally Posted by anon
By the way . . . if you just want a reasonably large buffer, instead of #define'ing your own size, you can use BUFSIZ from <stdio.h>. Apparently this is an efficient size for your system, and I'm pretty sure it's always at least 512.
Second one is correct. Array indexing starts with 0 in C and ends upto size-1 so there is no element buffer[SIZE], and hence you can't do the first one. Although neither of them will give compilation error because in C, there is no check to see if the subscript used for an array exceeds the size of the array.