0% found this document useful (0 votes)
82 views

Lecture 06

This document summarizes a lecture on pointers, arrays, and files in C++. It discusses pointers and how they point to objects in memory, pointer arithmetic, arrays and how they are related to pointers. It provides examples of using pointers with arrays and functions. It also discusses reading from and writing to files in C++ using input and output streams. The lecture covers three main topics: pointers and arrays, examples using arrays, and memory management techniques in C++.

Uploaded by

Martis88
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views

Lecture 06

This document summarizes a lecture on pointers, arrays, and files in C++. It discusses pointers and how they point to objects in memory, pointer arithmetic, arrays and how they are related to pointers. It provides examples of using pointers with arrays and functions. It also discusses reading from and writing to files in C++ using input and output streams. The lecture covers three main topics: pointers and arrays, examples using arrays, and memory management techniques in C++.

Uploaded by

Martis88
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

02393 C++ Programming

C++

Lecture 6:
Pointers, arrays and files.
Chapter 10:
Managing memory and low-level data structures

Christian W. Probst 1
Agenda
C++
  Pointers and arrays
  Pointers, Pointers to functions, Arrays,
Pointer arithmetic, Indexing, Array
initialization
  Examples for arrays
  String literals, array initialization, arguments

to main, reading and writing files


  Three kinds of memory management
  Allocating and deallocating objects and
arrays

6: Pointers, arrays and files 2


10.1 Pointers and arrays
C++

  An array is a kind of container


0 1 2 3 4

  These containers are created with the new expression


and disposed with the delete expression.

  A pointer points into a container and is a kind of random-


access iterator

  Pointers and arrays are the most primitive data structures in


C and C++

6: Pointers, arrays and files 3


10.1.1 Pointers
C++
A pointer is a value that represents the address of an object.

Every distinct object has a unique address in the memory (RAM)


of the computer

  If x is an object then &x is the address of that object


  If p is the address of an object then *p is the object itself

The & in &x is called address operator

The * is called dereference operator


  it works like * works when applied to any other iterator.
(Another way to dereference the object stored in p is p-> )

6: Pointers, arrays and files 4


10.1.1 Pointers (cont.)
C++
  If p contains the address of x, we also say that p is a
pointer that points to x:

p x

  A local variable with a pointer type has no meaningful


value until we initialize it:
  Often programmers give the pointer the value 0
  int * p = 0; //often called the null pointer

graphic notation for


p
the null pointer

6: Pointers, arrays and files 5


10.1.1 Pointers (cont.)
C++
Different ways to declare pointers:

int *p; // *p has type int

int* p; // p has type int*

int *p, q;
int* p, q;
int (*p), q;

int q; // 'q' a simple variable of type int


int *p; // 'p' is a pointer

6: Pointers, arrays and files 6


10.1.2 Pointers to functions
C++

int (*fp) (int);


//fp is a pointer to a
//function, which can take an int as
//argument and returns an int

int next (int n){


return n + 1;
}

fp = &next;
fp = next;

Functions that return pointers to functions are rare!


Please explore the subject in detail ($A.1/page 295)
if and when you need it in the future.

6: Pointers, arrays and files 7


10.1.3 Arrays
C++
  An array is a kind of a container – that is part of the core language
rather than part of the standard library
  Every array contains a sequence of one or more objects (elements)
of the same type
  If the array is declared in the code then its dimension must be
known at compile time:

double coords[3]; //a point in 3-dim space


*coords = 1.5 //sets the first
//element of cords to 1.5

  This shows the fundamental relationsship between arrays and


pointer
  coords without an index or without the * means the address of the
array's first element.
  *coords is the same as coords[0]

6: Pointers, arrays and files 8


10.1.4 Pointer Arithmetic
C++
  A pointer is a kind of iterator
  Can be incremented/decremented with ++/--

  A pointer is a random-access iterator

  If p points to the nth element of an array, then p+m points


to the (n + m)th element in the array
  assuming that the element exists

  BUT the compiler will not complain if the element does

NOT exist

6: Pointers, arrays and files 9


10.1.5 Indexing
C++
  The variable containing an array stores the address of the
first element of the array

  If a points to an array, then a[n] is the nth element of


the array
  If pointer p points to the mth element of an array, p[n] is
the address of the m+nth element of the array

  If p is a pointer and n is an integer then


p[n] is equivalent to *(p+n)

6: Pointers, arrays and files 10


10.1.6 Array initialization
C++
const int month_lengths[] = {
31, 28, 31, 30, 31, 30, 31,
31, 30, 31, 30, 31
}

int tabel[10][10];
for(int i=0, i < 10, i++)
for (int j=0; j <10, j++)
tabel[i][j] = (i+1)*(j+1);

6: Pointers, arrays and files 11


Agenda
C++
  Pointers and arrays
  Pointers, Pointers to functions, Arrays,
Pointer arithmetic, Indexing, Array
initialization
  Examples for arrays
  String literals, array initialization, arguments

to main, reading and writing files


  Three kinds of memory management
  Allocating and deallocating objects and
arrays

6: Pointers, arrays and files 12


10.2 String literals revisited
C++
  A string literal is really an array of const char
  with one more element than the number of characters in
the literal.

The extra character is the null character (i.e. '\0’ or binary zero)

const char hello[]={'H','e','l','l','o','\0'};

The variable hello has exactly the same ”meaning” as the


string literal "Hello"
BUT the two strings are really 2 different objects, and therefor
have different addresses.

6: Pointers, arrays and files 13


10.3 Initializing arrays of character pointers
C++
string letter_grade(double grade)
{
// range posts for numeric grades
static const double numbers[] = {
97, 94, 90, 87, 84, 80, 77, 74, 70, 60, 0
};

// names for the letter grades


static const char* const letters[] = {
"A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D", "F"
};

// compute the number of grades given the size of the array


// and the size of a single element
static const size_t ngrades = sizeof(numbers)/sizeof(*numbers);

// given a numeric grade, find and return the associated letter grade
for (size_t i = 0; i < ngrades; ++i) {
if (grade >= numbers[i])
return letters[i];
}

return "?\?\?";
}

6: Pointers, arrays and files 14


10. 4 Arguments to main
C++

int main(int argc, char** argv)


{
// if there are command-line arguments, write them
if (argc > 1) {
cout << argv[1]; // write the first argument

// write each remaining argument with a space before it


for (int i = 2; i != argc; ++i)
cout << " " << argv[i]; // 'argv[i]' is a 'char*'
}
cout << endl;
return 0;
}

6: Pointers, arrays and files 15


10.5 Reading and writing files
C++
The book uses cin and cout – and also some few different types of
files for input and putput (the standard input [stdin] and output
[stdout] are in the world of UNIX/LINUX considered as files)

  The keyboard is a file (the standard input file)


  The display is a file (the standard output file)
  A directory is a file
  The harddisk is a file
  The tapestation is a file
  The network is a file
  Etc…

6: Pointers, arrays and files 16


10.5.1 The standard error stream
C++

cerr or clog is used to write to the standard error streams

clog is more for logging purposes – accordingly it has the


same buffering as cout

The cerr stream always writes it output immediately


unless it is redirected:

$ exefile >2 logfailfile

6: Pointers, arrays and files 17


10.5.2 Dealing with multiple input and output
C++

#include <fstream> //and a lot of using:: xxx

int main()
{
ifstream infile("in");
ofstream outfile("out");

string s;

while (getline(infile, s))


outfile << s << endl;
return 0;
}

6: Pointers, arrays and files 18


Agenda
C++
  Pointers and arrays
  Pointers, Pointers to functions, Arrays,
Pointer arithmetic, Indexing, Array
initialization
  Examples for arrays
  String literals, array initialization, arguments

to main, reading and writing files


  Three kinds of memory management
  Allocating and deallocating objects and
arrays

6: Pointers, arrays and files 19


10.6 Three kinds of memorys managements
C++
1.  Automatic memory mangement
  associated with local variables
  Dont do this:
int * invalid_pointer() { int x; return &x; }//invalid

2.  Statically allocated


  associated with local variables
  A bit better, BUT

int * pointer_to_static(){
static int x; return &x; //Now better, but …..
}

3.  Dynamic allocation


  allocating and deallocating an object with new and delete
keywords

6: Pointers, arrays and files 20


10.6.1 Allocating and deallocation an object
C++
int * p = new int (42);
/*create a pointer p, which point to an object of type
int with the value 42
*/

++*p; // *p is now 43 (that is, the value of the object)

delete p; // the object is deleted

// every time invoked, create a new int object


int* pointer_to_dynamic() {
return new int(0);
}

6: Pointers, arrays and files 21


10.6.2 Allocating and deallocation an array
C++

T * p = new T[n];

If T is a type and n is a nonnegative integer, then


New T[n]
allocates an array of n objects of type T.
The pointer to the array is stored in p.

What does the following do if p points to an array of


type T?

vector <T> v(p, p+n);

delete[] p;

6: Pointers, arrays and files 22


Linked list
C++
  A single linked list consists of objects that are pointing to
each other:

  A typical list type would look like this:


struct listelem {
char data;
listelem* next
};

  What would we need to put in a class for single linked


lists?

6: Pointers, arrays and files 23


Linked list (cont.)
C++
class list {
public:
list(): h(0){} //0 denotes an empty list
void prepend(char c); // add to front of list
listelem* first() const {return (h);}
void del();
void print() const;
private:
listelem* h; // head of the list
}

The link member next points to next element in the list

6: Pointers, arrays and files 24


Linked list (cont.)
C++

The member function prepend is used to build the list


structure:

void list::prepend(char c) {
listelem* temp = new listelem; //create new elem
temp -> next = h;
temp -> data = c;
h = temp; //update head of list
}

6: Pointers, arrays and files 25


Linked list (cont.)
C++

The member function del has the role of deleting the


first element:

void del ()
{
listelem* temp = h;
h = h -> next;
delete temp;
}

6: Pointers, arrays and files 26


Linked list (cont.)
C++

void list::print()const //object is unchanged


{
listelem* temp = h;

while (temp !=0){ //detect end of list


cout << temp -> data << ”->”;
temp = temp -> next;
}
cout << ”\n###\n”;
}

6: Pointers, arrays and files 27


Linked list (cont)
C++

insertmid(’e’,3);
At first we add a new function insertmid
(char c, int pos), that takes a
character and an integer as arguments. The
new list element is inserted before the object
at position pos.

When a new element has to be inserted to


the list we have to
  create the element first and

  update the involved pointers.

It takes 3 steps and an extra helping pointer.

Implement this member functon as an extra


exercise 

6: Pointers, arrays and files 28


Linked list (cont.)
C++
Next let us look at the function deleteNext(int pos):

Starting point

First step

Last step

Try to imagine how to implement this function, do


implement it, and test it .

6: Pointers, arrays and files 29


10.7 Details
C++
  char** argv is the same as char * argv[ ]
  The second notation is only only legal as parameter type

  Memory management: new and delete


  When an object is no longer needed… delete it!

  Monday October 11th:


  Chapter 11: "Defining abstract datatypes.

6: Pointers, arrays and files 30

You might also like