Difficulty: Easy
Correct Answer: char p = (char)malloc(100);
Explanation:
Introduction / Context:
Dynamic memory allocation is a core C/C++ skill. Often, a pointer is declared and immediately assigned memory from the heap using malloc. This question tests whether you can correctly combine the declaration and the allocation into a single, syntactically valid statement while respecting type conversions and pointer syntax.
Given Data / Assumptions:
Concept / Approach:
malloc returns void. In C, an explicit cast is not required; in C++ it is required (or you should prefer new). A correct single statement must both declare p as a char and assign it the result of malloc converted to char*.
Step-by-Step Solution:
Start with the pointer declaration: char p;Allocate: p = (char)malloc(100);Combine: char p = (char)malloc(100);Ensure parentheses are around the cast, not around malloc's name.
Verification / Alternative check:
You can print p or test p != NULL (or p != nullptr in C++) to verify allocation. In C-only code, char *p = malloc(100); without a cast is also valid and idiomatic.
Why Other Options Are Wrong:
Common Pitfalls:
Forgetting to include stdlib.h (or cstdlib) for malloc, or failing to check allocation success. In C++, prefer new[] or smart pointers over malloc/free.
Final Answer:
char p = (char)malloc(100);.
Discussion & Comments