1.CPE6 Unit 2
1.CPE6 Unit 2
Data
Structures and
Algorithms
Pointers, Dynamic Memory Allocation,
Arrays, Structures
Week 2
Computer Engineering - CPE6
Week 2
Computer Engineering - CPE6
Intallation of C++
Week 2
Computer Engineering - CPE6
Week 2
Computer Engineering - CPE6
Pointers
A pointer is a variable whose value is the address of
another variable
Week 2
Computer Engineering - CPE6
&
symbol Variable Value Address
It returns the address of a variable if used
x 10 0x12345
before the variable name.
Usage:
int x = 10;
cout<< &x;
Week 2
Computer Engineering - CPE6
* symbol
Variable Value Address
It returns the value of a variable if used
before an address. x 10 0x12345
Usage:
int x = 10;
cout<< *(&x);
Week 2
Computer Engineering - CPE6
* symbol
Variable Value Address
It returns the value of a variable if used
before an address. x 10 0x12345
cout<< *ptr;
cout<< ptr;
Week 2
Computer Engineering - CPE6
Week 2
Computer Engineering - CPE6
Dynamic Memory
Allocation and Arrays
Dynamic Memory Allocation is the process of assigning the memory
space during the execution time or run time.
Week 2
Computer Engineering - CPE6
1. new
2. delete
3. new[]
4. delete[]
Week 2
Computer Engineering - CPE6
new
The new keyword is used to allocate a single object on the heap. Here’s how
you implement it.
Week 2
Computer Engineering - CPE6
delete
The delete keyword is used to deallocate memory that was previously allocated
using new. Here’s how you implement it.
delete num;
Week 2
Computer Engineering - CPE6
new[ ]
It is used to allocate memory for an array of objects on the heap.
Week 2
Computer Engineering - CPE6
delete[ ]
It is used to deallocate memory of the previous allocated memory using new[].
delete[] arr;
Week 2
Computer Engineering - CPE6
Example:
#include<iostream>
using namespace std;
int main() {
int *ptr = new int;
int *arr = new int[10];
Week 2
Computer Engineering - CPE6
Week 2
Computer Engineering - CPE6
Structure in C+
+
Structure is user-defined type which contains a collection
of variables with different data types under a single
name.
Week 2
Computer Engineering - CPE6
struct Person {
string fname;
string lname;
int age;
};
int main() {
Person person1;
person1.fname = "John";
person1.lname = "Smith";
person1.age = 30;
cout << "Name: " << person1.fname + " " + person1.lname<< endl;
cout << "Age: " << person1.age << endl;
return 0;
}
Week 2
Computer Engineering - CPE6
struct Person {
string name;
int age;
};
int main() {
Person people[3];
people[0] = {"Alice", 25};
people[1] = {"Bob", 30};
people[2] = {"Charlie", 28};
for (int i = 0; i < 3; ++i) {
cout << "Person " << i + 1 << ": Name = " << people[i].name << ", Age =
" << people[i].age << endl;
}
return 0;
}
Week 2
Computer Engineering - CPE6
THANKS!
DO YOU HAVE ANY QUESTIONS?
Week 2