0% found this document useful (0 votes)
2 views5 pages

Lect 5.1

ma

Uploaded by

3li
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)
2 views5 pages

Lect 5.1

ma

Uploaded by

3li
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/ 5

Array:

An array consists of a set of objects (called its elements), all of


which are of the same type and are arranged contiguously in
memory.
Strings:
A C++ string is simply an array of characters. For example,
char str[ ] = "HELLO";
examples of array in C++:
int sizeTemp[3]={3,4,5};
int seasonTemp[3][4] = {
{26, 34, 22, 17},
{24, 32, 19, 13},
{28, 38, 25, 10}
};

Pointers and References:


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.
*p refers to the content of variable p
&p refers to the address of variable p
Ex1: Example shows how pointer and references work in C++
#include <iostream>
using namespace std;
int main() {
int *pc, c;
c = 5;
cout<< "Address of c (&c): " << &c << endl;
cout<< "Value of c (c): " << c << endl << endl;

pc = &c; // Pointer pc holds the memory address of variable c


cout<< "Address that pointer pc holds (pc): "<< pc << endl;
cout<< "Content of the address pointer pc holds (*pc): " << *pc <<
endl << endl;

c = 11; // The content inside memory address &c is changed from 5


to 11.
cout << "Address pointer pc holds (pc): " << pc << endl;
cout << "Content of the address pointer pc holds (*pc): " << *pc <<
endl << endl;
*pc = 2;
cout<< "Address of c (&c): "<< &c <<endl;
cout<<"Value of c (c): "<< c<<endl<< endl;
return 0;
}
EX2: C++ program to swap two numbers using pass by pointer
#include <iostream>
using namespace std;
void swap(int* x, int* y)
{
int z = *x;
*x = *y;
*y = z;
}
int main()
{
int a = 45, b = 35;
cout << "Before Swap\n";
cout << "a = " << a << " b = " << b << "\n";
swap(&a, &b);
cout << "After Swap with pass by pointer\n";
cout << "a = " << a << " b = " << b << "\n";
}

You might also like