You are on page 1of 14

OBECT ORIENTED

PROGRAMMING
Lecture 03 Pointers
Dr. Faisal Shafait
Consultation Hours: Tue 4pm 5pm (DFKI lab)
faisal.shafait@seecs.edu.pk

Learn C++ by Examples

Examples demonstrate

How to display messages


How to obtain information from the user
How to perform arithmetic calculations

Spring 2015

CS 212

Spring 2015

CS 212

printf

Spring 2015

CS 212

std::cout

Spring 2015

CS 212

Pointers
int nasir, younis, afridi, haris;
int *mazhar;
afridi = 28;
nasir = 0;
younis = nasir;
mazhar = &nasir;
haris = *mazhar;

Spring 2015

28

afridi

nasir

haris

CS 212

1500

younis

mazhar
6

Learn by Examples
int a = 5, b = 10;
int *p1, *p2;
p1 = &a;
p2 = &b;
*p1 = 10;
p1 = p2;
*p1 = 20;
printf("a = %d\n", a);
printf("b = %d\n", b);
Spring 2015

CS 212

Learn by Examples
int main()
{
int n = 310;
funcOne(n);
cout << n = << n << endl;
return 0;
}
void funcOne(int n) {
n = 240;
}
Spring 2015

CS 212

Learn by Examples
int main()
{
int n = 310;
funcOne(n);
funcTwo(&n);
cout << n =
<< n << endl;
return 0;
}

Spring 2015

void funcOne(int n)
{
n = 240;
}
void funcTwo(int *n)
{
n = 120;
}

CS 212

Learn by Examples
Memory Implication?
Assign 15 x 1 bytes
consecutively in the memory

void printHelloWorld() {
char helloWorld[] = Hello, werld!\n;
helloWorld[8] = o;
std::cout << helloWorld;
}
hello.h

Spring 2015

CS 212

10

Learn by Examples
void printHelloWorld() {
char helloWorld[] = Hello, werld!\n;
helloWorld[8] = o;
std::cout << helloWorld;
}
hello.h
#include <iostream>
int main (int argc,
char** argv) {
printHelloWorld();
return 0;
}
Spring 2015

CS 212

#include hello.h

program.cpp
11

Learn by Examples
void printHelloWorld() {
char helloWorld[] = Hello, vorld!\n;
*(helloWorld + ?) = w;
std::cout << helloWorld;
}
hello.h

How to change the string to Hello, my world! ?

Spring 2015

CS 212

12

Memory Allocation
#include <string.h>
#include <malloc.h>
void printHelloWorld() {
char* helloWorld = (char)* malloc(20);
strncpy(helloWorld, Hello, world!\n, 20);
std::cout << helloWorld;
free(helloWorld);
}

Spring 2015

CS 212

13

Allocating int arrays


#include <string.h>
#include <malloc.h>
20*sizeof(int)
void printHelloWorld() {
int* helloWorld = (int)* malloc(20);
std::cout << helloWorld[10];
free(helloWorld);
}

Spring 2015

CS 212

14

You might also like