I don't understand how this code works:

for (int i = 50; i >= 0; i--)
    char s[3];

    // convert i from int to string
    sprintf(s, "%i", i);

Why do we need 3 characters to store 50 numbers?

  • This is not storing 50 numbers. s stores a string which represents a single number. Each iteration of the loop generates a new string from the number i and stores it in s. Aug 22 '14 at 7:47

Because the last char in the array is the NULL character ('\0') to signify the end of the string. You always need a string of length + 1 characters to account for this NULL character.


You must log in to answer this question.

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