ProgrammingHardWipro · Cognizant pattern

Assume a 64-bit LP64 ABI. What is printed?

Assume a 64-bit LP64 ABI. What is printed?
typedef struct {
    int code;
    char message[20];
} Error;
Error makeError(int c, const char *msg) {
    Error e;
    e.code = c;
    strncpy(e.message, msg, 19);
    e.message[19] = '\0';
    return e;
}
int main(void) {
    Error e = makeError(404, "Not Found");
    printf("%d %s", e.code, e.message);
}
  1. A. 0
  2. B. 404
  3. C. Compilation error: cannot return a local struct containing an array
  4. D. 404 Not Found

Correct answer: D. 404 Not Found

Returning a struct by value (even one containing a fixed-size array member) copies the ENTIRE struct's bytes out of the function; there's no dangling-pointer issue here since nothing is returned by reference. e.code=404 and e.message="Not Found" are both correctly copied out.

More C Programming questions

Exams that ask this topic