[go: up one dir, main page]

0% found this document useful (0 votes)
22 views37 pages

References and Pointers

The document provides an overview of computer programming concepts in C++, focusing on references, pointers, and memory management. It covers topics such as call-by-value and call-by-reference, the use of the '&' operator to access memory addresses, and the differences between references and pointers. Additionally, it includes code examples demonstrating pointer arithmetic and dynamic memory allocation.

Uploaded by

villanerror767
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views37 pages

References and Pointers

The document provides an overview of computer programming concepts in C++, focusing on references, pointers, and memory management. It covers topics such as call-by-value and call-by-reference, the use of the '&' operator to access memory addresses, and the differences between references and pointers. Additionally, it includes code examples demonstrating pointer arithmetic and dynamic memory allocation.

Uploaded by

villanerror767
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

INDIAN INSTITUTE OF TECHNOLOGY ROORKEE

CEC-101: Computer Programming


References, pointers and memory

Prof. Anjaneya Dixit


anjaneya.dixit@ce.iitr.ac.in
A quick recap

• Programming basics in C++ (input/output)


• Data types, variables, operators
• Conditional and iterative statements
• (if-else, switch)
• (for, do-while, while)
• Strings,
• Arrays
• Function (Syntax, parameters, calling, overloading)

1. Call by value
• Passing the value directly as argument
• Passing the value using variable as argument:
2. Call by reference (send the variable itself as the argument)

2
Accessing Memory Address in C++

• Variable declaration → Memory address is assigned to the variable


• Variable assignment → Value is stored in the memory address

• This address can be accessed using ‘&’ operator

string food = "Pizza";


cout << &food; //Outputs 0x6ffe00 or similar hexadecimal form

• & operator can be used to get the memory address of a variable


i.e., the location where the variable is stored on the computer.

3
References in C++
• A reference variable is a "reference" to an existing variable, and it
is created with the & operator
• The reference itself isn't an object (it has no identity; taking the
address of a reference gives you the address of the referent)

string food = "Pizza"; // food variable


string &meal = food; // reference to food (another name for food)

cout << food << "\n"; // food variable


cout << meal << "\n"; // reference to food
cout << &meal << "\n"; // address of meal

food = “Pasta";
TODO: Check the memory address
cout << food << "\n"; of variable and reference variable.
cout << meal << "\n";

4
Call-by-value vs call-by-reference
The formal parameters for a function are
• Listed in the function declaration
• Used in the body of the function definition. A formal parameter (of any sort) is a
• Kind of blank or placeholder that is filled in with something when the function is called.

An argument is something that is


• Listed in parentheses after the function name
• Used to fill in a formal parameter
• “plugged in” for the formal parameters when the function call is executed

Call-by-value and call-by-reference are mechanisms used in the “plugging in” process.
• In call-by-value method, only the value of the argument is used. The formal parameter is
a local variable that is initialized to the value of the corresponding argument.
• In call-by-reference method, the argument is a variable, and the entire variable is used.
The argument variable is substituted for the formal parameter so that any change that is
made to the formal parameter is actually made to the argument variable.

5
Call-by-value vs call-by-reference
• With the call-by-value, ➔ the function takes only the value of
the variable and does not change the variable in any way

• With the call-by-reference ➔ formal parameters are called as


reference parameters ➔ the corresponding argument in a
function call must be a variable

6
References in C++

• References and pointers in C++ give you the ability to manipulate


the data in the computer's memory - which can reduce the code
and improve the performance.

7
References in C++

void figure_me_out(int &x, int y, int &z) {


using namespace std;
cout << x << " " << y << " " << z << endl;
x = 1;
y = 2;
z = 3;
cout << x << " " << y << " " << z << endl;
}
int main( ) {
int a, b, c;
a = 10;
b = 20;
c = 30;
figure_me_out(a, b, c);
cout << a << " " << b << " " << c;
return 0;
}
Output of this program?

8
Pointers

• When the variable is used as a call-by-reference argument,


it is this address, not the identifier name of the variable, that
is passed to the calling function.

• An address that is used to name a variable in this way (by


giving the address in memory where the variable starts)
is called a pointer because the address can be thought of as
“pointing” to the variable.

• When a variable is a call-by-reference argument in a function


call, the function is given this argument variable in the form of
a pointer to the variable.

9
Pointers in C++

10
Pointers

• A variable to hold a pointer must be declared to have a


pointer type.
Type_Name *Variable_Name1, *Variable_Name2, . . .;

• you cannot perform the normal arithmetic operations on


pointers

• You can assign the value of one pointer variable to another


pointer variable. This copies an address from one pointer
variable to another pointer variable.

11
Pointers in C++

string food = "Pizza"; // A food variable of type string


string* ptr = &food; // A pointer variable, same type as that of
food variable with the name ptr, that stores the memory address of
food

// Output the value of food (Pizza)


cout << food << "\n";

// Output the memory address of food (0x6dfed4)


cout << &food << "\n";

// Output the memory address of food with the pointer (0x6dfed4)


cout << ptr << "\n";

12
Dereference in C++

• It is also possible to use the pointer to get the value of the


variable, by using the * operator (dereference * operator).

string food = "Pizza"; // Variable declaration


string* ptr = &food; // Pointer declaration

// Reference: Output the memory address of food with the pointer (0x6dfed4)
cout << ptr << "\n";

// Dereference: Output the value of food with the pointer (Pizza)


cout << *ptr << "\n";

•When used in declaration (string* ptr), it creates a pointer variable.

•When not used in declaration, it act as a dereference operator.

13
Modify pointers in C++
string food = "Pizza";
string* ptr = &food;

// Output the value of food (Pizza)


cout << food << "\n";

// Output the memory address of food (0x6dfed4)


cout << &food << "\n";

// Access the memory address of food and output its value (Pizza)
cout << *ptr << "\n";

// Change the value of the pointer


*ptr = "Hamburger";

// Output the new value of the pointer (Hamburger)


cout << *ptr << "\n";

// Output the new value of the food variable (Hamburger)


cout << food << "\n";
14
Modify pointers in C++
• Since a pointer can be used to refer to a variable, your program can manipulate variables
even if the variables have no identifiers to name them.

• The operator new can be used to create variables that have no identifiers to serve as their
names.

int *ptr = new int;


dynamic variables

cin >> *ptr;


*ptr = *ptr + 7;
cout << *ptr;

15
Modify pointers in C++

16
Modify pointers in C++

17
Modify pointers in C++

Which one is correct?

Order of precedence …

18
Double pointers in C++

19
Double pointers in C++
int var = 20; // variable declaration and assignment
int *ptr; // pointer declaration
ptr = &var; // pointer assignment

cout << "Value at ptr = " << ptr << "\n";


cout << "Value at var = " << var << "\n";
cout << "Value at *ptr = " << *ptr << "\n";

*ptr = 30; // dereference ptr and assigning new value


cout << "Value at var = " << var << "\n";

int **ptr2 = &ptr; // pointer declaration and assignment

cout << "Value at ptr2 = " << ptr2 << "\n";


cout << "Value at *ptr2 = " << *ptr2 << "\n";
cout << "Value at **ptr2 = " << **ptr2 << "\n";

**ptr2 = 40; // dereference ptr and assigning new value


cout << "Value at var = " << var << "\n";

20
Pointers in C++

There are 3 ways to pass C++ arguments to a function:

•call-by-value

•call-by-reference with pointer argument

•call-by-reference with reference argument

21
Pointers in C++: Call-by-value
#include <iostream>
using namespace std;
int square (int n){
cout << "Address of n in square(): " << &n << endl;
n *= n;
return n;
}
int main() {
int n1 = 8;
cout << "Address of n1 in main(): " << &n1 << endl;
int sq = square(n1);
cout << "Square of n1: " << sq << endl;
cout << "Double check value of n1: " << n1 << endl;
return 0;
}

22
Pointers in C++: Call-by-reference (Reference)
#include <iostream>
using namespace std;
void square (int &n){
cout << "Address of n1 in square(): " << &n << endl;
n *= n;
}
int main() {
int n1 = 8;
cout << "Address of n1 in main(): " << &n1 << endl;
square(n1);
cout << "Square of n1: " << n1 << endl;
cout << “Modified value of n1: " << n1 << endl;
return 0;
}

23
Pointers in C++: Call-by-reference (Pointers)
#include <iostream>
using namespace std;
void square (int *n){
cout << "Address of n1 in square(): " << n << endl;
*n *= *n;
}
int main() {
int n1 = 8;
cout << "Address of n1 in main(): " << &n1 << endl;
square(&n1);
cout << "Square of n1: " << n1 << endl;
cout << “Modified value of n1: " << n1 << endl;
return 0;
}

24
References vs Pointers

#include <iostream> #include <iostream>


using namespace std; using namespace std;
int main(){ int main(){

int num = 25; int num = 25;


int &refnum = num; int *ptrnum = &num;
cout << refnum << endl; cout << *ptrnum << endl;

refnum = 30; *ptrnum = 30;


refnum += 5; *ptrnum += 5;

cout << num << endl; cout << num << endl;
cout << refnum << endl; cout << *ptrnum << endl;
return 0; return 0;
} }

25
Pointers vs References in C++

#include <iostream>
using namespace std;
int main() {
int i = 10; //Simple variable
int *p = &i; //Single pointer /* All the above pointers differ in the
int **pt = &p; // Double pointer value they store or point to */
int ***ptr = &pt; //Triple pointer
cout << "i= " << i << "\t" << "p= " << p << "\t" << "pt= " << pt << "\t" <<
"ptr= " << ptr << "\n";

int j = 10;
int &s = j; /* All the above references do not differ in the
int &s0 = s; value as they refer to the same variable */
int &s1 = s0;
cout << "j= " << j << "\t" << "s= " << s << "\t" << "s0= " << s0 << "\t" <<
"s1= " << s1 << "\n";
return 0;}

26
Null Pointer in C++

• It is considered a good practice to assign the pointer NULL to a pointer variable in case
exact address to be assigned to the pointer is unavailable.

• This is done at the time of variable declaration.

• A pointer that is assigned NULL is called a null pointer.

int *ptr = NULL;

• One can perform error handling in pointer related code e.g., dereference pointer variable
only if it’s not NULL

if (ptr) {
cout << “Pointer is not null."; Will pointer to a null pointer is
} also NULL?
if (ptr!=NULL) { char* np = NULL;
cout << “Pointer is not null."; char** pnp = &np;
}

27
Pointers to Arrays in C++

This is also called as arithmetic pointers


(incremental or decremental)

28
Pointers to Arrays in C++

#include <iostream>
using namespace std;
int main(){
int arr [3] = {5, 10, 20}; //Declare array
int *ptr = arr; //Declare pointer and assign to 1st element of arr

cout << "Elements of the array: " << endl;


cout << ptr [0]<< " " << ptr [1] << " " << ptr[2] << endl;

cout << ptr << endl;


cout << ptr+1 << endl;
cout << ptr+2 << endl;
return 0;
}

Pointer is an address which is a


value, thus, limited arithmetic
operations can be performed.

29
Pointer Arithmetic in C++ (Incremental)

#include <iostream>
using namespace std;
int main(){
int arr [3] = {5, 10, 20}; //Declare array
int *ptr = arr; //Declare pointer and assign to 1st element of arr

cout << "Elements of the array: " << endl;


cout << ptr [0]<< " " << ptr [1] << " " << ptr[2] << endl;

cout << ptr << endl;


cout << ptr+1 << endl;
cout << ptr+2 << endl;
return 0;
}

Try to understand the output of the following:


cout << ptr <<" "<< ptr+1 <<" " << ptr+2 <<endl;
cout << ptr[0] <<" "<<ptr[1] <<" " << ptr[2] <<endl;
cout <<*ptr <<" "<<*(ptr+1) <<" " <<*(ptr+2) <<endl;
cout <<*ptr+1 <<" "<<*(ptr+1)+1 << " " << *(ptr+2)+2;

30
Pointer Arithmetic in C++ (Decremental)

#include <iostream>
using namespace std;
int main(){
int arr [3] = {5, 10, 20}; //Declare array
int *ptr = &arr[2]; //Declare pointer and assign to 1st element of arr

cout << "Elements of the array: " << endl;


cout << ptr [0]<< " " << ptr [-1] << " " << ptr[-2] << endl;

cout << ptr << endl;


cout << ptr-1 << endl;
cout << ptr-2 << endl;

cout << *ptr << endl;


cout << *(ptr-1) << endl;
cout << *(ptr-2) << endl;

return 0;
}

31
Pointer Arithmetic in C++

The increment (or decrement) in


the memory address shall
depend on the pointer data type

32
Pointer Arithmetic in C++

st nd
*p++ // same as *(p++): 1 dereference current address, 2 pointer increment
st nd
*++p // same as *(++p): 1 pointer increment, 2 dereference update address
st nd
++*p // same as ++(*p): 1 dereference current address, 2 pre-increment the value
st nd
(*p)++ // 1 dereference current address, 2 post-increment the value

33
Pointer Arithmetic in C++
st nd
*p++ // same as *(p++): 1 dereference current address, 2 pointer increment
st nd
*++p // same as *(++p): 1 pointer increment, 2 dereference update address
st nd
++*p // same as ++(*p): 1 dereference current address, 2 pre-increment the value
st nd
(*p)++ // 1 dereference current address, 2 post-increment the value

#include <iostream>
using namespace std;
int main(){
int arr [3] = {5, 10, 20}; //Declare array
int *ptr = arr; //Declare pointer and assign to 1st element of arr
cout << "Elements of the array: " << endl;
cout << ptr [0]<< " " << ptr [1] << " " << ptr[2] << endl;
cout << ptr << endl;
cout << ptr+1 << endl;
cout << ptr+2 << endl;

int x= (*ptr)++;
cout << ptr << endl;
cout <<x<<endl;

return 0;
}
34
Pointer Comparison in C++

Pointer is an address which is a value, thus,


relational operations (==, >, <) can be
performed.

#include <iostream>
using namespace std;
int main(){
int arr [3] = {5, 10, 20}; //Declare array
int *ptr = arr; //Declare pointer and assign to 1st element of arr

cout << "Elements of the array: " << endl;


cout << ptr [0]<< " " << ptr [1] << " " << ptr[2] << endl;

cout << ptr << endl;


cout << ptr+1 << endl;
cout << ptr+2 << endl;

if (ptr <= ptr+1) cout << "TRUE";


return 0;
}

35
Pointers in C++

int arr [3][4] = {


{11,22,33,44},
{55,66,77,88},
{11,66,77,44}
};

36
Pointer to 2D array in C++

Watch: https://www.youtube.com/watch?v=sHcnvZA2u88
37

You might also like