My code works, but dont know why it is char filename[7]. Why 7? Why not another number?Thanks.
// create filename
char filename[7];
sprintf(filename, "%03i.jpg", jpg_number);
[snip out unneeded code]
CS50 Stack Exchange is a question and answer site for students of Harvard University's CS50. It only takes a minute to sign up.
Sign up to join this communityMy code works, but dont know why it is char filename[7]. Why 7? Why not another number?Thanks.
// create filename
char filename[7];
sprintf(filename, "%03i.jpg", jpg_number);
[snip out unneeded code]
Should be char filename[8]
. You need three characters for the digits, four for the .jpg
, and one for the null terminator marking the string end.
It still works with 7 as probably the next byte in memory is unused (variables might be placed at memory addresses divisible by 2, 4, or 8, depending on type, as those can be faster to access). Otherwise, you'd overwrite a byte of another variable with the null terminator (a byte of zero).
\0
. If it is longer, it works fine, but that's just a waste of memory. ;-) Occasionally, I'll use a couple extra chars "just in case", if I'm not sure,UNLESS it's in something that is allocated repeatedly, but I'll usually fix it later.
– Cliff B
Aug 9 '18 at 21:16