Answers for "pointers vs references in c++"

C++
1

pointers vs references in c++

#include<iostream>

/*
Pointers: *ptr, point to the memory location of a variable
int a = 10
int *ptr = &a //points to the location in memory (0x80ea or whatever) 
instead of the value

in order for pointers to work, the variable it's pointing to needs to 
be de-referenced using &.(If confused, remember that the variable, int a, 
is itself a reference to the location of the value you set it to).

A reference variable: &ref, points to another variable.

int b = 20;
int &ref = b // points to the value of b, which is 20.

run this if confused:
*/

    int a = 10;
    int *ptr = &a;
    std::cout << "int a value: " << a << std::endl;
    std::cout << "int ptr value: " << ptr << std::endl;

    int b = 20;
    int& ref = b;
    std::cout << "int b value: " << b << std::endl;
    std::cout << "int ref value: " << ref << std::endl;

    ref = a;
    std::cout << "int ref after setting it equal to a: " << ref << std::endl;
    ref = *ptr;
    std::cout << "int ref after setting it equal to *ptr: " << ref << std::endl;
    ptr = &ref;
    std::cout << "ptr after setting it equal to &ref: " << ptr << std::endl; 
    ptr = &b;
    std::cout << "ptr after setting it equal to &b: " << ptr << std::endl;

/*
Reference variables CANNOT be set to a pointer variable; In the case above, you 
see we can't just put ref = ptr; ptr HAS to be dereferenced with a *, which in 
turn will give us the value of a, or 10. (dereference pointers with *)

Same goes for pointer variables being set to a reference; you have to dereference 
the reference value (ptr = &b instead of ptr = b;). In the block above, when we 
set ptr = &ref, the ref variable is dereferenced showing us a memory location. 
When ptr=&b is called and we see the output, we noticed it is the same as the previous 
output.
*/
Posted by: Guest on September-10-2021
1

difference between pointer and reference in c++

Pointers: 
A pointer is a variable that holds memory address of another variable. 
A pointer needs to be dereferenced with * operator to access the 
memory location it points to. 

References :
 A reference variable is an alias, that is, 
another name for an already existing variable.
 A reference, like a pointer, is also implemented 
by storing the address of an object.
Posted by: Guest on May-14-2021

Browse Popular Code Answers by Language