1

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]

3

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).

1
  • 1
    Actually, it needs to be at least 8. The filenames are all 7 chars long, plus 1 for the end of string marker, \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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .