+ 2

c++

What is the difference between int* ptr and int &ref in C++?

13th Feb 2025, 3:50 PM
darius franklin
darius franklin - avatar
2 Answers
+ 3
darius franklin Both are similar in that they access a variable stored in another memory address, BUT the differences are much more significant. ref is a CONSTANT alias to the variable it is assigned at declaration and initialization. No memory is allocated to ref, just an entry in lookup table that replaces ref with the other variable. You don't need to do anything special with ref to access the variable, they are interchangeable. int x = 5; int& ref = x; // no memory allocated cout << x; // prints 5 cout << ref; // also prints 5 ptr is an actual variable with its own allocated memory. It stores a memory address, instead of a value of the specified type. As a variable, you can assign it different memory address values at any time. To access the value of the address ptr points to, you have to explicitly dereference ptr. int x = 5; int* ptr = &x; // memory allocated, stores address of x cout << x; // prints 5 cout << *ptr; // retrieves value stored at memory pointed at, also prints 5
13th Feb 2025, 10:45 PM
Shardis Wolfe
+ 1
darius franklin those are pointers which stores the address of the another variables. Here int* ptr is the pointer variable called ptr where asterisk (*) is the keyword used for the pointer variable. And int &ref retrieves the stored address of the another variable and the keyword is ampersand(&).
13th Feb 2025, 6:46 PM
Aysha