Practice mode C Language

What is printed by this C code: int *p = calloc(4, sizeof *p); p += 5; printf(“%d”, p + p + p); free(p);?

Correct answer A. 5

Explanation

calloc(4, sizeof *p) allocates room for four ints and sets every byte to zero, so all elements start at 0. Adding 5 to p[1] gives the sum 0 + 5 + 0 = 5. With malloc the elements would be indeterminate. Writing sizeof *p instead of sizeof(int) keeps the call correct if the type of p changes later. Production code should also check p against NULL.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.