Reputation: 1250
As far as I know, fprintf
takes an pointer to a array of chars as an argument, and prints it. I don't know "when" it stops though. Take the following examples:
Assume: print_s
is
void print_s(const char* s) {
fprintf(stdout,"%s",s);
}
Example 1:
char c[6];
c[0] = 'a';
c[1] = 'b';
c[2] = 'c';
c[3] = 'd';
c[4] = 'e';
print_s((char*) c);
output:
abcd // e not printed!
Example 2:
char c[6];
c[0] = 'a';
c[1] = 'b';
c[2] = 'c';
c[3] = 'd';
c[4] = 'e';
c[5] = 'b';
print_s((char*) c);
output:
abcdb // works as expected
Example 3:
char c[6];
c[0] = 'a';
c[2] = 'c';
c[3] = 'd';
c[4] = 'e';
print_s((char*) c);
output:
a<someGarbage>cd // works as expected
Example 4:
char c[6];
c[0] = 'a';
c[1] = 'b';
c[2] = 'c';
c[3] = 'd';
c[4] = 'e';
c[5] = '\0';
print_s((char*) c);
output:
abcde // works as expected
Upvotes: 2
Views: 136
Reputation: 15198
Section '7.19.6.1 The fprintf function 8(s)', top of page 280, of the ISO/IEC 9899 C standard I looked at has the following to say about strings printed by fprintf()
(using the %s
format specifier):
Characters from the array are written up to (but not including) the terminating null character. If the precision is specified, no more than that many bytes are written. If the precision is not specified or is greater than the size of the array, the array shall contain a null character (emphasis mine).
Even the behaviour you note as 'expected' is unspecified if the NUL terminator is absent. The behaviour you are seeing is dependent the implementation of the compiler and that of the system your code is running on. On different system or with a different compiler, you are likely to get a different result for your examples 1-3.
Upvotes: 0
Reputation: 2251
Please note that when you declare character arrays and initialize their elements one-by-one, you need to provide values for the characters continuously starting from the first one, and the last character should be given a null '\0'
value.
Example:
char a[6];
a[0]='a';
a[1]='b';
a[2]='c';
a[3]='d';
a[4]='\0';
This would declare the array a
as the string "abcd"
.
If you fail to initialize in a similar way, your string is prone to getting garbage character values, which cannot be correctly interpreted by any I/O function, and would give unexpected results.
Upvotes: 6