You are on page 1of 8

Fundamental Programming Language with C++

• Pointers as function arguments


Sending by value
#include <iostream>
using namespace std;
void func(int a, int b){
a+=5; a a
b+=5; 0x28fefc 10 0x280b11 10 15
}
b b
int main()
0x28fe0c 20 0x33412 20 25
{
int a=10; 0
y1
int b=20; Cop
func(a,b); 20
py
Co

cout<<a<<endl<<b;

} 10
20
• Pointers as function arguments
Sending by reference
#include <iostream>
using namespace std;
void func(int *a, int *b){ 15
*a+=5; a *a
*b+=5; 0x28fefc 10 0x280b11 0x28fef
} c
25
b *b
int main()
0x28fe0c 20 0x33412 0x28fe0c
{
int a=10; dr ess
y ad
int b=20; Cop ss
re
func(&a,&b); add
py
Co

cout<<a<<endl<<b;

}
15
25
• Pointers with Array p 0x28fefc
4 byte
int a=10; int a[5]; a
int *b; int *p; 0x28fefc
p=a; 1 a[0]
b=&a;
cout<< a; 0x28ff00 2 a[1]
cout<< a; --- 10 cout<< a [0];
0x28ff04 3 a[2]
#include <iostream> #include <iostream>
using namespace std; using namespace std; 0x28ff08 4 a[3]
int main() int main()
{ { 0x28ff0c 5 a[4]
int a[5]={1,2,3,4,4}; int a[5]={1,2,3,4,4};
cout << a; cout << a[0];
} 0x28fefc } 1

#include <iostream> #include <iostream>


using namespace std; using namespace std;
int main() int main()
{ {
int a[5]={1,2,3,4,4}; int a[5]={1,2,3,4,5};
cout << &a[0]; int *p;
cout << &a[1]; 0x28fefc p=a;
cout << &a[2]; 0x28ff00 cout << a<<endl;
cout << &a[3]; 0x28ff04 cout<<p;
cout << &a[4]; 0x28ff08 } 0x28fefc
} 0x28ff0c 0x28fefc
Examples:
#include <iostream>
using namespace std;
void func(int x[]){
for (int i=0; i<5; i++)
x[i]=x[i]*x[i];
}

int main()
{
int a[5]={1,2,3,4,5};
func(a); p 0x28fefc
4 byte
for (int i=0; i<5; i++)
a
cout<<a[i]<<" ";
0x28fefc 1 a[0]
} 1 4 9 16 25
0x28ff00 2 a[1]
• Pointers Arithmetic
0x28ff04 3 a[2]

0x28ff08 4 a[3]

0x28ff0c 5 a[4]
Examples:
#include <iostream>
using namespace std;

int main()
{
int a[5]={10,2,3,4,5};
int*p;
p=a;
cout <<a<<endl;
cout <<p<<endl;
cout <<*p<<endl;
cout <<*p+1<<endl;
cout <<*(p+1)<<endl;
cout <<*(p+2)<<endl; 0x28fef8
cout <<*(p+3)<<endl; 0x28fef8
10
cout <<*(p+4)<<endl; 11
2
3
4
} 5
• Pointers with Structures
Example:
#include <iostream>
s1
#include <string>
using namespace std; saddam
struct student {
45
string name;
int age; 80.5
float deg1;
};
int main()
{ student s1;
s1.name="Saddam";
s1.age=45;
s1.deg1=80.5;
student *p;
p=&s1;
cout<< "Name"<<" "<<"Age"<<" "<<"Deg1"<< endl;
cout <<p->name<<" "<<p->age<<" "<<p->deg1<< endl;
return 0;
}
Name Age Deg1
Saddam 45 80.5
Example2:
#include <iostream>
using namespace std;
struct student {
string name;
int age;
float deg1;
};
void func(student *s){ s-> age++; saddam
} 21
int main()
{ student s1;
s1.name="saddam";
s1.age=20;
s1.deg1=88;
student*p;
p=&s1;
func(&s1);
cout<<p->name<<endl;
cout<<p->age;
return 0;
}

You might also like