WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

C++ · Basic · question 4 of 100

What is a pointer, and how do you declare and use one in C++?

📕 Buy this interview preparation book: 100 C++ questions & answers — PDF + EPUB for $5

A pointer is a variable that holds the memory address of another variable. In C++, pointers are used to manipulate memory directly and to pass data by reference. Pointers are a powerful feature of the C++ language, but they can also be a source of errors and bugs if not used correctly.

To declare a pointer variable in C++, you use the * operator followed by the variable name. For example:

    int *myPointer;

This declares a pointer variable called myPointer that can hold the memory address of an integer variable.

To assign a value to a pointer variable, you use the & operator followed by the variable name. This returns the memory address of the variable, which can be assigned to the pointer variable. For example:

    int myInt = 42;
    int *myPointer = &myInt;

This assigns the memory address of the integer variable myInt to the pointer variable myPointer.

To access the value of the variable that the pointer points to, you use the * operator followed by the pointer variable name. For example:

    int myInt = 42;
    int *myPointer = &myInt;
    std::cout << "Value of myInt: " << myInt << std::endl; // prints 42
    std::cout << "Value of *myPointer: " << *myPointer << std::endl; // prints 42

This first prints the value of the integer variable myInt (which is 42), and then prints the value of the variable that myPointer points to (which is also 42).

Pointers can also be used to dynamically allocate memory at runtime using the new operator. For example:

    int *myPointer = new int;
    *myPointer = 42;
    std::cout << "Value of *myPointer: " << *myPointer << std::endl; // prints 42
    delete myPointer;

This dynamically allocates memory for an integer variable, assigns the value 42 to it using the * operator, prints the value using std::cout, and then frees the memory using the delete operator.

In summary, pointers are a powerful feature of C++ that allow you to manipulate memory directly and to pass data by reference. To declare a pointer, you use the * operator followed by the variable name. To assign a value to a pointer, you use the & operator followed by the variable name. To access the value of the variable that the pointer points to, you use the * operator followed by the pointer variable name. Pointers can also be used to dynamically allocate memory at runtime using the new and delete operators.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic C++ interview — then scores it.
📞 Practice C++ — free 15 min
📕 Buy this interview preparation book: 100 C++ questions & answers — PDF + EPUB for $5

All 100 C++ questions · All topics