Data Structures (Second Part)
Lecture 2 : Pointers
Bong-Soo Sohn
Assistant Professor
School of Computer Science and Engineering
Chung-Ang University
Pointer
Pointers
Pointer Operators
* (dereference operator) : Unary * takes the contents of a pointer
(dereferences a pointer)
& (reference operator) : Unary & gives the address of (pointer to) something
Declaring variables of pointer types
Variables that contain memory addresses
Declare which data type a pointer is going to point to
// ‘a’ is a variable that stores an address of
(ex) int* a;
// an integer type variable.
float* b;
void swap(int* x, int* y);
NULL Pointer?
C++ example 1
// more pointers
#include <iostream>
using namespace std;
int main ()
{
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;
p1 = &firstvalue; // p1 = address of firstvalue
p2 = &secondvalue; // p2 = address of secondvalue
*p1 = 10; // value pointed by p1 = 10
*p2 = *p1; // value pointed by p2 = value pointed by p1
p1 = p2; // p1 = p2 (value of pointer is copied)
*p1 = 20; // value pointed by p1 = 20
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
return 0;
}
---------Output :
firstvalue is 10
secondvalue is 20
Pointers and Arrays
Array variable is a constant pointer
the identifier of an array is equivalent to the address of its first element
(ex)
int numbers[20];
int *p;
p=numbers;
// OK
numbers=p;
// NOT OK!
numbers[5]=0;
*(numbers+5)=0;
*p=1;
p++;
*p=2;
// numbers [offset of 5] = 0;
// value pointed by (numbers+5) = 0;
C++ example 2
// more pointers
#include <iostream>
using namespace std;
int main ()
{
int numbers[5];
int * p;
p = numbers;
*p = 10; p++;
*p = 20;
p = &numbers[2];
*p = 30;
p = numbers + 3;
*p = 40;
p = numbers;
*(p+4) = 50;
for (int n=0; n<5; n++)
cout << numbers[n] << ", ";
return 0;
}
Output :
10, 20, 30, 40, 50,
Pointers to Pointers
C++ allows the use of pointers that point to pointers
char a;
char * b;
char ** c;
a = 'z';
b = &a;
c = &b;
c has type char** and a value of 8092
*c has type char* and a value of 7230
**c has type char and a value of 'z'
© Copyright 2025 Paperzz