ProgrammingModerate
Which call reads a line into char buf[100] safely?
- A. gets(buf)
- B. scanf("%s", buf)
- C. fgets(buf, sizeof buf, stdin)
- D. fgets(buf, 1000, stdin)
Correct answer: C. fgets(buf, sizeof buf, stdin)
fgets is given the real capacity, so it never writes more than 100 bytes. gets is unbounded and removed from C11, scanf %s stops only at whitespace, and the 1000 limit overflows the 100-byte buffer.
More C Programming questions
- char name[10]; / input: a long name / scanf("%9s", name); What is the most characters stored before the terminator?
- Records (name, score, age) are sorted by score descending, and by age ascending for equal scores. Input: (A,90,30), (B,90,25), (C,85,20)…
- qsort is used on an array of records where several records have equal keys. Which statement is guaranteed by the C standard?
- A sorted array of struct items is searched with bsearch for a key that is not in the array. What does bsearch return?
- An array struct P ps[] of pointers to records is to be sorted by an int field k with qsort. Which comparator is correct?
- For struct R { char c; short s; int i; } with natural alignment (char 1, short 2, int 4), what is sizeof(struct R)?