CPlusPlus / Pointers

CPlusPlus / Pointers#

  1. What advantages does nullptr provide over NULL or using the value 0?

    nullptr is a pointer literal of type std::nullptr_t, which can be implicitly converted to any pointer type. This makes it more type-safe than NULL or 0. Additionally, nullptr cannot be implicitly converted to integral types, helping to prevent certain programming errors.

  2. What happens if you dereference a null pointer?

    It results in undefined behavior, often causing a program crash.

  3. How do you dynamically allocate memory for a single integer in C++?

    int* ptr = new int;

  4. How do you free dynamically allocated memory in C++?

    Use ‘delete’ for single objects and ‘delete[]’ for arrays.

  5. What is the difference between int const ptr and const int* ptr?*

    int* const ptr is a constant pointer to an int, while const int* ptr is a pointer to a constant int.