C++_Session7.ppt

25
Let us Session -VII

Transcript of C++_Session7.ppt

Page 1: C++_Session7.ppt

Let us

Session -VII

Page 2: C++_Session7.ppt

Agenda

Pointers Arrays using Pointers Enumeration Typedef

Page 3: C++_Session7.ppt

Pointers Pointers are the powerful feature of C++ programming.

To understand pointers, we should have the knowledge of address in computer memory. Computer memory is broken down into bytes and each byte has its own address.

EX: In 1KB memory, there are 1024 bytes and each byte is given an address (0 - 1023).

The Address-of Operator &

The & operator can find address occupied by a variable. If var is a variable then, &var gives the address of that variable.

Page 4: C++_Session7.ppt

Pointer Variables

Pointer variables or simply pointers are the special types of variable that holds memory address instead of data.

Like any variable or constant, you must declare a pointer before you can work with it. The general form of a pointer variable declaration is:

type *var-name; Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of the pointer variable. The asterisk (*) is a dereference operator which means pointer to.

Ex: int *p; Here pointer p is a pointer to int, that is, it is pointing an integer.

Page 5: C++_Session7.ppt

Pointer Assignments As with any variable, you may use a pointer on the right-hand side

of an assignment statement to assign its value to another pointer.

#include iostreamusing namespace std;int main(void){ int x; int *p1, *p2; p1 = &x; p2 = p1; cout<< p2; /* print the address of x, not x's value! */ return 0;}

Both p1 and p2 now point to x.

Page 6: C++_Session7.ppt

Pointer Arithmetic There are only two arithmetic operations that you may use

on pointers: 1)addition and 2)subtraction.

Each time a pointer is incremented, it points to the memory location of the next element of its base type.

Each time it is decremented, it points to the location of the previous element.

Ex: int *p; p++; p--; This approach ensures that a pointer is always pointing to an

appropriate element of its base type.

Page 7: C++_Session7.ppt

Pointer Arithmetic You may add or subtract integers to or from pointers. The

expression p1 = p1 + 12; makes p1 point to the 12th element of p1's type beyond the one it

currently points to.

Besides addition and subtraction of a pointer and an integer, only one other arithmetic operation is allowed: You may subtract one pointer from another in order to find the number of objects of their base type that separate the two.

All other arithmetic operations are prohibited. Specifically, you may not multiply or divide pointers; you may not add two pointers; you may not apply the bitwise operators to them; and you may not add or subtract type float or double to or from pointers.

Page 8: C++_Session7.ppt

Pointers and Arrays In essence, C/C++ provides two methods of accessing array

elements: 1) pointer arithmetic and 2) array indexing.

Although the standard array-indexing notation is sometimes easier to understand, pointer arithmetic can be faster. Since speed is often a consideration in programming.

C/C++ programmers commonly use pointers to access array elements.

Consider this program fragment: char str[80], *p1; p1 = str; Here, p1 has been set to the address of the first array element in

str. To access the fifth element in str, you could write str[4] or *(p1+4)

Page 9: C++_Session7.ppt

Pointers and Arrays Both statements will return the fifth element. Remember, arrays

start at 0. To access the fifth element, you must use 4 to index str. You also add 4 to the pointer p1 to access the fifth element because p1 currently points to the first element of str.

an array name without an index returns the starting address of the array, which is the address of the first element.

Relation between Arrays and Pointers

int arr[4];

Page 10: C++_Session7.ppt

Arrays of Pointers Pointers may be arrayed like any other data type. The

declaration for an int pointer array of size 10 is int *x[10];

To assign the address of an integer variable called var to the third element of the pointer array, write

x[2] = &var;

To find the value of var, write *x[2]

Page 11: C++_Session7.ppt

Multiple Indirection You can have a pointer point to another pointer that points to the

target value. This situation is called multiple indirection, or pointers to pointers.

A variable that is a pointer to a pointer must be declared as such. You do this by placing an additional asterisk in front of the variable name.

For example, the following declaration tells the compiler that newbalance is a pointer to a pointer of type float:

float **newbalance;

You should understand that newbalance is not a pointer to a floating-point number but rather a pointer to a float pointer.

To access the target value indirectly pointed to by a pointer to a pointer, you must apply the asterisk operator twice, as in this example:

Page 12: C++_Session7.ppt

Example#include iostreamusing namespace std;int main(void){

int x, *p, **q;x = 10;p = &x;q = &p;Cout<<**q; /* print the value of x */return 0;

}

Page 13: C++_Session7.ppt

Initializing Pointers After a local pointer is declared but before it has been assigned a

value, it contains an unknown value. (Global pointers are automatically initialized to null.)

There is an important convention that most C/C++ programmers follow when working with pointers: A pointer that does not currently point to a valid memory location is given the value null (which is zero). By convention, any pointer that is null implies that it points to nothing and should not be used.

Page 14: C++_Session7.ppt

Pointers to Functions A function pointer is the powerful feature of C++ Even though a function is not a variable, it still has a physical

location in memory that can be assigned to a pointer. This address is the entry point of the function and it is the address

used when the function is called. Once a pointer points to a function, the function can be called

through that pointer. Function pointers also allow functions to be passed as arguments

to other functions. Pointers to functions are declared with the same syntax as a

regular function declaration, except that the name of the function is enclosed between parentheses () and an asterisk (*) is inserted before the name

int (*Compare)(const char*, const char*);

Page 15: C++_Session7.ppt

You can obtain the address of a function by using the function's name without any parentheses or arguments.

EX: strcmp; or &strcmp

int (*Compare)(const char*, const char*); defines a function pointer named Compare which can hold the

address of any function that takes two constant character pointers as arguments and returns an integer.

The string comparison library function strcmp, for example, is such.Therefore:

Compare = &strcmp; // Compare points to strcmp function The & operator is not necessary and can be omitted: Compare = strcmp; // Compare points to strcmp function

Pointers to Functions

Page 16: C++_Session7.ppt

Pointers to Functions Alternatively, the pointer can be defined and initialized at once: int (*Compare)(const char*, const char*) = strcmp;When a function address is assigned to a function pointer, the two types must match. The above definition is valid because strcmp has a matching function prototype: int strcmp(const char*, const char*);Given the above definition of Compare, strcmp can be either called directly, or indirectly via Compare. The following three calls are equivalent: 1) strcmp("Tom", "Tim"); // direct call 2) (*Compare)("Tom", "Tim"); // indirect call 3) Compare("Tom", "Tim"); // indirect call (abbreviated)A common use of a function pointer is to pass it as an argument to another function;

Page 17: C++_Session7.ppt

void Pointers The void type of pointer is a special type of pointer. In C++, void

represents the absence of type. Therefore, void pointers are pointers that point to a value that has no type (and thus also an undetermined length and undetermined dereferencing properties).

This gives void pointers a great flexibility, by being able to point to any data type, from an integer value or a float to a string of characters.

In exchange, they have a great limitation: the data pointed to by them cannot be directly dereferenced (which is logical, since we have no type to dereference to), and for that reason, any address in a void pointer needs to be transformed into some other pointer type that points to a concrete data type before being dereferenced.

One of its possible uses may be to pass generic parameters to a function.

Page 18: C++_Session7.ppt

Typedef You can create a new name for an existing type using typedef. Following is the simple syntax to define a new type using

typedef: typedef type newname; For example, the following tells the compiler that feet is another

name for int: typedef int feet; Now, the following declaration is perfectly legal and creates an

integer variable called distance: feet distance; Now that feet has been defined, it can be used in another

typedef. For example, typedef feet height; tells the compiler to recognize height as another name for feet,

which is another name for int.

Page 19: C++_Session7.ppt

Enumeration An enumeration is a set of named integer constants that specify all

the legal values a variable of that type may have Enumerations are defined much like structures; the keyword enum

signals the start of an enumeration type.

The general form for enumerations is enum enum-type-name { enumeration list } variable_list; Here, both the type name and the variable list are optional. (But at

least one must be present.) The following code fragment defines an enumeration called coin: enum coin { penny, nickel, dime, quarter,half_dollar, dollar };

Page 20: C++_Session7.ppt

Enumeration The enumeration type name can be used to declare variables of its

type. In C,the following declares money to be a variable of type coin. enum coin money; In C++, the variable money may be declared using this shorter

form: coin money; In C++, an enumeration name specifies a complete type. In C, an

enumeration name is its tag and it requires the keyword enum to complete it.

The key point to understand about an enumeration is that each of the symbols stands for an integer value. As such, they may be used anywhere that an integer may be used.

Each symbol is given a value one greater than the symbol that precedes it. The value of the first enumeration symbol is 0.

Page 21: C++_Session7.ppt

Enumeration You can specify the value of one or more of the symbols by using

an initializer. Do this by following the symbol with an equal sign and an integer

value. Symbols that appear after initializers are assigned values greater

than the previous initialization value. For example, the following code assigns the value of 100 to

quarter: enum coin { penny, nickel, dime, quarter=100,half_dollar, dollar }; Now, the values of these symbols are

symbols value

penny 0

nickel 1

dime 2

quarter 100

half_dollar 101

dollar 102

Page 22: C++_Session7.ppt

Enumeration Since enumeration values must be converted manually to their

human-readable string values for I/O operations, they are most useful in routines that do not make such conversions.

An enumeration is often used to define a compiler's symbol table

Enumerations are also used to help prove the validity of a program by providing a compile-time redundancy check confirming that a variable is assigned only valid values.

Page 23: C++_Session7.ppt

Summary

In this session we have learned Pointers Arrays using Pointers, Enumeration and Typedef

Page 24: C++_Session7.ppt
Page 25: C++_Session7.ppt

Assignment- 11,12&13

Assignments using pointers, arrays of pointers Assignments on passing pointers in functions. Using pointers write your own functions for the

following;º String comparisonº String concatenateº String copyº String length