Sobes.tech
Junior — Middle

What is the difference between a pointer and a reference in programming?

sobes.tech AI

Answer from AI

A pointer is a variable that stores the memory address of another object. It can be modified, redirected to different objects, and pointer arithmetic can be performed (for example, moving to the next element of an array).

A reference is an alternative name for an existing variable. It must be initialized upon creation and cannot be reassigned to another object. References are safer because they do not allow null values or arithmetic.

Example in C++:

int a = 10;
int* ptr = &a; // pointer to a
int& ref = a;  // reference to a

*ptr = 20; // changes a through the pointer
ref = 30;  // changes a through the reference

Main difference: a pointer can be null and can change the address it points to; a reference always refers to one object and cannot be changed after initialization.