tags:

views:

94

answers:

1

why 9 is a must in char input[9]

int getInput (void) {
    char input[9];
    fgets(input, 9, stdin);
    return atoi(input + 6);
}


void printHeader(void) {
    printf("Content-type: text/html\n\n");
    printf("<html>\n");
    printf("<head>\n");
    printf("<title>%s</title>\n", PROGRAM_NAME);
    printf("</head>\n");
    printf("<body style='padding:25px;'>\n");
}

void printFooter(void) {
    printf("</body>\n");
    printf("</html>\n");
}

int main() {
    int n=0;
    int last1 = 0;
    int last2 = 1;
    int current;
    int max_n = getInput();

    printHeader();
    printf("<h2>%s</h2>\n", PROGRAM_NAME);
    printf("The first %d Fibonacci numbers are: \n", max_n);
    printf("<br />");

    while (n < max_n) {
        if (n == 0) {
            current = 0;        
        } else if (n == 1) {
            current = 1;
        } else {
            current = last2 + last1;
        }
        printf("%d, ", current);
        last1 = last2;
        last2 = current;
        n++;
    }
    printf("...\n");
    printFooter();
    return 0;
}
+2  A: 

It's not. It just means the buffer is 9 chars. fgets needs to know that to avoid a buffer overflow. It can read 8 chars, because 1 is needed for NUL. It would be cleaner to write:

int getInput (void) {
    char input[9];
    fgets(input, sizeof(input), stdin);
    return atoi(input + 6);
}

to avoid redundancy.

If you make the buffer smaller, you clearly may not be able to read all the input, which is why the program no longer works correctly. If it's larger, there may be (more) unused buffer space.

The + 6 means atoi starts reading from the 7th char.

Matthew Flaschen
but change to 8, the program will not function correctly.
friends
output result char input[9] (input 47 in forms) 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, ... output result char input[8] (input 10 in forms) 0, ...
friends
if i enter 9 in web forms, how big is the "9" char?if i enter 10 in web forms, how big is the "10" char?
friends
char [9] means 9 bit or byte?
friends
9 bytes..........
Kinderchocolate