C what the function of this function? [closed]
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;
}
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.
精彩评论