In C/C++, can the two statements 'char p;' and 'p = (char) malloc(100);' be combined into a single declaration-and-initialization statement? Select the correctly formed combined statement.

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:

  • You need 100 bytes allocated from the heap.
  • Pointer type should be char because the memory will be treated as an array of bytes.
  • The code may be compiled as C or C++ (casting rules differ slightly).


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:

  • char p = malloc(100); dereferences void and stores a single char—wrong type/semantics.
  • char *p = (char) malloc(100); casts to char, losing pointer value.
  • char p = (char )(malloc)(100); invents a non-existent type (malloc), invalid syntax.


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);.

More Questions from Pointers

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion