Sobes.tech
Junior — Middle

Can you list and explain the main types of pointers in programming languages?

sobes.tech AI

Answer from AI

In programming languages, especially in C/C++, pointers are variables that store addresses of other variables or objects in memory. Main types of pointers:

  1. Object pointer (data pointer) — stores the address of a variable or object. Allows indirect access to data.

  2. Function pointer — stores the address of a function, enabling calling the function through the pointer.

  3. Null pointer — a special value indicating that the pointer does not point to any object.

  4. Pointer to pointer — a pointer that stores the address of another pointer.

  5. Constant pointers and pointers to constants:

    • int * const p — constant pointer, the address cannot change, but data can.
    • const int * p — pointer to a constant, data cannot be changed, but the address can.

Example of an object pointer:

int a = 10;
int *p = &a; // p stores the address of a
std::cout << *p; // outputs 10

Example of a function pointer:

void func() { std::cout << "Hello"; }
void (*fptr)() = func;
fptr(); // call the function through the pointer

Pointers provide a powerful tool for working with memory, dynamic data structures, and functions.