POINTERS. // Chapter 3 - Program 1 - POINTERS.CPP #include int main() { int *pt_int; float *pt_float; int pig = 7, dog = 27; float x = 1.2345, y = 32.14;

Slides:



Advertisements
Similar presentations
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Advertisements

Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Kernighan/Ritchie: Kelley/Pohl:
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
Informática II Prof. Dr. Gustavo Patiño MJ
Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Chapter 9. 2 Objectives You should be able to describe: Addresses and Pointers Array Names as Pointers Pointer Arithmetic Passing Addresses Common Programming.
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Lecture 2 Pointers Pointers with Arrays Dynamic Memory Allocation.
1 ES 314 Advanced Programming Lec 3 Sept 8 Goals: complete discussion of pointers discuss 1-d array examples Selection sorting Insertion sorting 2-d arrays.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into.
CS Data Structures Chapter 4 Lists.
Pointers Applications
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Overview Working directly with memory locations is beneficial. In C, pointers allow you to: change values passed as arguments to functions work directly.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
Copyright  Hannu Laine C++-programming Part 3 Hannu Laine.
Comp 245 Data Structures Linked Lists. An Array Based List Usually is statically allocated; may not use memory efficiently Direct access to data; faster.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
Pointers review Let a variable aa be defined as ‘int *aa;’, what is stored in aa? Let a variable aa be defined as ‘int ** aa;’ what is stored in aa? Why.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
CPSC 252 Dynamic Memory Allocation Page 1 Dynamic memory allocation Our first IntVector class has some serious limitations the capacity is fixed at MAX_SIZE.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
Object-Oriented Programming in C++
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
1 Pointers to structs. 2 A pointer to a struct is used in the same way as a pointer to a simple type, such as an int. Pointers to structs were introduced.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Pointers *, &, array similarities, functions, sizeof.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved This Weeks Topics: Pointers (continued)  Modify C-String through a function call 
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
CCSA 221 Programming in C CHAPTER 11 POINTERS ALHANOUF ALAMR 1.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
You learned how to declare pointer variables how to store the address of a variable into a pointer variable of the same type as the variable how to manipulate.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Dynamic Allocation in C
Pointers.
Pointers Revisited What is variable address, name, value?
Dynamic Memory Allocation
Object Oriented Programming COP3330 / CGS5409
Pointers, Dynamic Data, and Reference Types
Overloading functions
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

POINTERS

// Chapter 3 - Program 1 - POINTERS.CPP #include int main() { int *pt_int; float *pt_float; int pig = 7, dog = 27; float x = , y = 32.14; void *general; pt_int = &pig; *pt_int += dog; cout << "Pig now has the value of " << *pt_int << "\n"; general = pt_int;

pt_float = &x; y += 5 * (*pt_float); cout << "y now has the value of " << y << "\n"; general = pt_float; const char *name1 = "John"; // Value cannot be changed char *const name2 = "John"; // Pointer cannot be changed return 0; }

pointers A pointer in either ANSI-C or C++ is declared with an asterisk preceding the variable name. The pointer is then a pointer to a variable of that one specific type and should not be used with variables of other types. Thus pt_int is a pointer to an integer type variable and should not be used with any other type. int *pt_int; Of course, an experienced C programmer knows that it is simple to coerce the pointer to be used with some other type by using a cast, but he must then assume the responsibility for its correct usage.

In the first line the pointer named pt_int is assigned the address of the variable named pig The second line uses the pointer named pt_int to add the value of dog to the value of pig because the asterisk dereferences the pointer in exactly the same manner as standard C. Figure 3-1 is a graphical representation of the data space following execution of line 13. Note that a box containing a dot represents a pointer. pt_int = &pig; *pt_int += dog;

The address is used to print out the value of the variable pig in line 14 cout << "Pig now has the value of " << *pt_int << "\n"; illustrating the use of a pointer with the output stream object cout. Likewise, the pointer to float named pt_float is assigned the address of x, then used in a trivial calculation in line pt_float = &x; y += 5 * (*pt_float); //y=38,3125

POINTERS TO CONSTANTS The definition of C++ allows a pointer to a constant to be defined such that the value to which the pointer points cannot be changed but the pointer itself can be moved to another variable or constant. The method of defining a pointer to a constant is illustrated in line const char *name1 = "John"; // Value cannot be changed

POINTERS TO CONSTANTS Const int conint =10; Const int *pt1 = &conint; Pt1=&pig; //pointer can point to another constant or variable //conint =12; // the value of constant cannot be changed Pig=9; char c; c=‘x’; const char *name1=“John”; *name1 = “Johnson”; // illegal name1 = “Johnson”; //legal name1 = &c;

CONSTANT POINTERS In addition to a pointer to a constant, you can also declare a constant pointer, one that cannot be changed. Line 23 illustrates this. char *const name2 = "John"; // Pointer cannot be changed If a pointer will never be moved due to its nature, we should define it as a constant pointer. If a value will not be changed, it can be defined as a constant and the compiler will tell you if you ever inadvertently attempt to change it.

CONSTANT POINTERS int *const ptcon = &pig; //ptcon = &dog //ptcon &pig pig =20; char *const name2 = “John”; //*name2 = “John1”; //name2 = “John1”; char c, c1; c=‘x’; c1=‘y’; //name2 = &c; char *const name2=&c; //name2 = &c1; c= ‘z’;

A POINTER TO VOID The pointer to void is actually a part of the ANSI-C standard A pointer to void can be assigned the value of any other pointer type. void *general; Note that the pointer to void named general is assigned an address of an int type in line general = pt_int; and the address of a float type in line general = pt_float; with no cast and no complaints from the compiler. This is a relatively new concept in C and C++. It allows a programmer to define a pointer that can be used to point to many different kinds of things to transfer information around within a program.

malloc() function The malloc() function returns a pointer to void. This pointer can be assigned to point to any entity, thus transferring the returned pointer to the correct type. A pointer to void is aligned in memory in such a way that it can be used with any of the simple predefined types available in C++, or in ANSI-C for that matter. They will also align with any compound types the user can define since compound types are composed of the simpler types.

// Chapter 3 - Program 2 - NEWDEL.CPP #include struct date { int month; int day; int year; }; int main() { int index, *point1, *point2; point1 = &index; *point1 = 77; point2 = new int; *point2 = 173; cout << "The values are " << index << " " << *point1 << " " << *point2 << "\n"; point1 = new int; point2 = point1; *point1 = 999; cout << "The values are " << index << " " << *point1 << " " << *point2 << "\n"; delete point1; float *float_point1, *float_point2 = new float;

float_point1 = new float; *float_point2 = ; *float_point1 = 2.4 * (*float_point2); delete float_point2; delete float_point1; date *date_point; date_point = new date; date_point->month = 10; date_point->day = 18; date_point->year = 1938; cout month day << "/" << date_point->year << "\n"; delete date_point; char *c_point; c_point = new char[37]; delete [ ] c_point; c_point = new char[sizeof(date) + 133]; delete [ ] c_point; return 0; }

The new and delete operators The new and delete operators do dynamic allocation and deallocation in much the same manner that the malloc() and free() functions do in C implementation. During the design of C++, it was felt that since dynamic allocation and deallocation are such a heavily used part of the C programming language and would also be heavily used in C++, it should be a part of the language, rather than a library add-on. The new and delete operators are actually a part of the C++ language and are operators, much like the addition operator or the assignment operator. They are therefore very efficient, and are very easy to use as we will see in this example program.

Pointers - Examples Lines point1 = &index; *point1 = 77; illustrate the use of pointers in the tradition of C and line point2 = new int; illustrates the use of the new operator. This operator requires one modifier which must be a type as illustrated here. The pointer named point2 is now pointing at the dynamically allocated integer variable which exists on the heap, and can be used in the same way that any dynamically allocated variable is used in ANSI-C. Lines *point2 = 173; cout << "The values are " << index << " " << *point1 << " " << *point2 << "\n"; illustrate displaying the value on the monitor which was assigned in line 18.

Pointers - Examples Line point1 = new int; allocates another new variable and line point2 = point1; causes point2 to refer to the same dynamically allocated variable as point1 is pointing to. In this case, the reference to the variable that point2 was previously pointing to has been lost and it can never be used or deallocated. It is lost on the heap until we return to the operating system when it will be reclaimed for further use, so this is obviously not good practice.

The delete operator Note that point1 is deallocated with the delete operator in line, delete point1; and point2 can not be deleted since it is now pointing to nothing. Since the pointer point1 itself is not changed, it is probably still pointing to the original data on the heap. This data could probably be referred to again using point1, but it would be terrible programming practice since you have no guarantee what the system will do with the pointer or the data. The data storage is returned to the free list to be allocated in a subsequent call, and will soon be reused in any practical program.

The delete operator delete point1; Since the delete operator is defined to do nothing if it is passed a NULL value, it is legal to ask the system to delete the data pointed to by a pointer with the value of NULL, but nothing will actually happen. It is actually wasted code. The delete operator can only be used to delete data allocated by a new operator. If the delete is used with any other kind of data, the operation is undefined and anything can happen. According to the ANSI standard, even a system crash is a legal result of this illegal operation, and can be defined as such by the compiler writer.

Pointers - Examples In line, float *float_point1, *float_point2 = new float; we declare some floating point variables. A declaration is an executable statement and can therefore appear anywhere in a list of executable statements. One of the float variables is allocated within the declaration to illustrate that this can be done. Some of the same operations are performed on these float type variables as were done on the int types earlier.

Pointers - Examples One may use: (*date_point).month = 10; Some examples of the use of a structure date *date_point; date_point = new date; date_point->month = 10; date_point->day = 18; date_point->year = 1938; cout month day << "/" << date_point->year << "\n"; delete date_point; and should be self explanatory.

new with different size Finally, since the new operator requires a type to determine the size of the dynamically allocated block, you may wonder how you can allocate a block of arbitrary size. c_point = new char[37]; where a block of 37 char sized entities, which will be 37 bytes, is allocated. A block of 133 bytes greater than the size of the date structure is allocated in line 50. c_point = new char[sizeof(date) + 133]; It is therefore clear that the new operator can be used with all of the flexibility of the malloc() function which you are familiar with. The brackets are required in lines delete [] c_point; to tell the compiler that it is deallocating an array.

malloc(), calloc(), and free() functions The standard functions which you have been using in C for dynamic memory management, malloc(), calloc(), and free(), are also available for use in C++ and can be used in the same manner they were used in C. If you are updating code with the older function calls, continue to use them for any additions to the code. If you are designing and coding a new program you should use the newer constructs because they are a built in part of the language rather than an add on and are therefore more efficient. It is an error to delete a variable that has been malloc'ed and it is an error to free a variable that was allocated with new.

// Chapter 3 - Program 3 - FUNCPNT.CPP #include void print_stuff(float data_to_ignore); void print_message(float list_this_data); void print_float(float data_to_print); void (*function_pointer)(float); int main() { float pi = ; float two_pi = 2.0 * pi; print_stuff(pi); function_pointer = print_stuff; function_pointer(pi); function_pointer =print_message; function_pointer(two_pi); function_pointer(13.0); function_pointer = print_float; function_pointer(pi); print_float(pi); return 0; }

void print_stuff(float data_to_ignore) { printf("This is the print stuff function.\n"); } void print_message(float list_this_data) { printf("The data to be listed is %f\n", list_this_data); } void print_float(float data_to_print) { printf("The data to be printed is %f\n", data_to_print); }

Pointers - Examples There is nothing unusual about this program except for the pointer to a function declared in line void (*function_pointer)(float); This declares a pointer to a function which returns nothing (void) and requires a single formal parameter, a float type variable. Note that all three of the functions declared in lines void print_stuff(float data_to_ignore); void print_message(float list_this_data); void print_float(float data_to_print); fit this profile and are therefore candidates to be called with this pointer.

Observe that in line print_stuff(pi); we call the function print_stuff() with the parameter pi and in line 15 function_pointer = print_stuff; // line 15 we assign the function pointer named function_pointer the value of print_stuff and use the function pointer to call the same function again in function_pointer(pi); Lines print_stuff(pi); function_pointer(pi); are therefore identical in what is accomplished because of the pointer assignment in line 15.

Pointers - Examples In lines, function_pointer = print_message; function_pointer(two_pi); function_pointer(13.0); function_pointer = print_float; function_pointer(pi); print_float(pi); a few more illustrations of the use of the function pointer are given.

A function name is a pointer to that function Since we assigned the name of a function to a function pointer, and did not get an assignment error, the name of a function must be a pointer to that function. This is exactly the case. A function name is a pointer to that function, but it is a pointer constant and cannot be changed. This is exactly the case we found when we studied arrays in ANSI-C at some point in our C programming background. An array name is a constant pointer to the first element of the array.

Since the name of the function is a constant pointer to that function, we can assign the name of the function to a function pointer and use the function pointer to call the function. The only caveat is that the return value and the number and types of parameters must be identical. Most C and C++ compilers will not, and in fact, can not warn you of type mismatches between the parameter lists when the assignments are made. This is because the assignments are done at runtime when no type information is available to the system, rather than at compile time when all type information is available. The use and operation of pointers must be thoroughly understood when we get to the material on dynamic binding and polymorphism later in this tutorial. It will be discussed in detail at that time.