ProgrammingHard
A string of up to 10^6 characters is read with fgets. Which buffer declaration is correct?
- A. static char line[1000000];
- B. char line[10];
- C. static char line[1000001]; without any room for the newline check
- D. static char line[1000002];
Correct answer: D. static char line[1000002];
One byte is needed for the terminator and fgets may keep a newline, so 10^6 + 2 bytes is safe. Exactly 10^6 bytes leaves no room for the terminator of a full-length line.
More C Programming questions
- A loop walks a string with for (i = 0; i < strlen(s); i++) on a string of length 10^6. What is the total cost?
- A binary search on the answer in [1, 10^18] computes mid = (lo + hi) / 2 with long long. Is this safe?
- A sum of n = 10^5 terms is stored in a double. Is this a safe choice for exact integer sums up to 10^14?
- A loop reads n numbers and stores them in int a[n] as a VLA of size up to 10^6 inside main. What is the main risk?
- To sort 10^6 integers with qsort, which comparator is correct for all int values?
- A counting pass over an array of 10^7 values, each in [0, 9], uses 10 counters. Which statement is correct?