Docsity

Pointers to Pointers-Introduction To Programming-Lecture Notes, Study notes of Computer Programming

Toggle sidebar
bg1
Lecture No. 16
Reading Material
Deitel & Deitel - C++ How to Program Chapter 5, 18
5.9, 5.10, 18.4
rays
nters to Pointers
x Command-line Arguments
x Exercises
)
l continue with the elaboration of the concept of pointers in this lecture. To
rther understand pointers, let's consider the following statement.
;
es it with a string. Remember the
achieve the same thing with the
Summary
x Pointers (continued)
x Multi-dimensional Ar
x Poi
x Tips
Pointers (continued
We wil
fu
char myName[] = "Full Name"
This statement creates a 'char' type array and populat
character strings are null ( '\0' ) terminated. We can
use of pointer as under:
char * myNamePtr = "Full Name";
Full Name\0
Full Name\0
myName
myNamePtr
Let's see what's the difference between these two approaches?
When we create an array, the array name, 'myName' in this case, is a constant pointer.
The starting address of the memory allocated to string "FullName" becomes the
171
docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Pointers to Pointers-Introduction To Programming-Lecture Notes and more Study notes Computer Programming in PDF only on Docsity!

Lecture No. 16

Reading Material

Deitel & Deitel - C++ How to Program Chapter 5, 18

rays nters to Pointers  Command-line Arguments  Exercises

l continue with the elaboration of the concept of pointers in this lecture. To rther understand pointers, let's consider the following statement.

;

es it with a string. Remember the achieve the same thing with the

Summary

 Pointers (continued)  Multi-dimensional Ar  Poi

 Tips

Pointers (continued

We wil fu

char myName[] = "Full Name"

This statement creates a 'char' type array and populat character strings are null ( '\0' ) terminated. We can use of pointer as under:

char * myNamePtr = "Full Name";

Full Name\

myName Full Name\

myNamePtr

Let's see what's the difference between these two approaches? When we create an array, the array name, 'myName' in this case, is a constant pointer. The starting address of the memory allocated to string "FullName" becomes the

docsity.com

cation to which array names points to an not be changed. In the second statement, the 'myNamePtr' is a pointer to a string

ays

s discussed above, the array name points to the starting memory location of the emory allocated for the array elements. Here the question arises where the 'multi' ill be pointing if we add 1 to ‘multi’.

e know that a pointer is incremented by its type number of bytes. In this case, ulti' is an array of 'char' type that takes 1 byte. Therefore, ‘muti+1’ should take us to

contents of the array name 'myName' and the array name 'myName' can not be assigned any other value. In other words, the lo c "FullName", which can always be changed to point to some other string.

Hence, the array names can be used as pointers but only as constant ones.

Multi-dimensional Arr Now we will see what is the relationship between the name of the array and the pointer. Suppose we have a two-dimensional array:

char multi[5][10];

In the above statement, we have declared a 'char' type array of 5 rows and 10 columns.

[0] [1] [2] [3] [5] [6] [7] [8] [9] [0]

A

m w

W 'm the second element of the first row (row 0). But this time, it is behaving differently. It is pointing to the first element (col 0) of the second row (row 1). So by adding '1' in the array name, it has jumped the whole row or jumped over as many memory locations as number of columns in the array. The width of the columns depends upon the type of the data inside columns. Here, the data type is 'char', which is of 1 byte. As the number of columns for this array 'multi' is 10, it has jumped 10 bytes.

Remember, whenever some number is added in an array name, it will jump as many rows as the added number. If we want to go to the second row (row 1) and third column (col 2) using the same technique, it is given ahead but it is not as that straight forward. Remember, if the array is to be accessed in random order, then the pointer approach may not be better than array indexing.

We already know how to dereference array elements using indexing. So the element at second row and third column can be accessed as 'multi[1][2]'.

[4]

1 st^ row 1st^ col 2 nd^ row 1 st^ col

Multi-dimensional array in the memory

[ 1]

docsity.com

ptr = *multi; // ‘ptr’ is assigned the starting address of the first row

for (int { mult

co }

/* Array ma cout "\n Array manipulated using pointer is: \n";

/* Initialize the array elements */ for(int i=0; i < 5; i++) { j=0; j < 10; j++)

i[i][j] = i * j; } }

/* Array manipulation using indexing */ cout << "\n Array manipulated using indexing is: \n"; for(int i=0; i < 5; i++) { for (int j=0; j < 10; j++) { cout << multi[i][j] << '\t'; } ut << '\n';

nipulation using pointer */ << for(int k=0; k < 50; k++, ptr ++) // 5 * 10 = 50 { cout << *ptr << '\t'; } }

The output of this program is: Array manipulated using indexing is: 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 0 2 4 6 8 10 12 14 16 18 0 3 6 9 12 15 18 21 24 27 0 4 8 12 16 20 24 28 32 36

Array manipulated using pointer is: 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 0 2 4 6 8 10 12 14 16 18 0 3 6 9 12 15 18 21 24 27 0 4 8 12 16 20 24 28 32 36

The above line of output of array manipulation is wrapped because of the fixed width of the table. Actually, it is a single line. Why it is a single line? As discussed in the previous lectures, computer stores array in straight line (contiguous memory locations). This straight line is just due to the fact that a function accepting a multi-dimensional array as an argument, needs to know all the dimensions of the array except the leftmost one. In case of two-dimensional array,

docsity.com

e function needs to know the number of columns so that it has much information bout the end and start of rows within an array.

is recommended to write programs to understand and practice the concepts of ouble dereferencing, single dereferencing, incrementing the name of the array to ccess different rows and columns etc. Only hands on practice will help understand e concept thoroughly.

ointers to Pointers hat we have been talking about, now we will introduce a new terminology, is

n case of single dereference, the value of the pointer is the address of the variable at contains the value desired as shown in the following figure. In the case of pointer nter contains the address of the second the address of the variable, which contains the desired value.

o Pointers are very useful. But you need to be very careful while using the

ount the students of e of the array as the number of students, say 53. Being look ahead and think about the maximum size of the

th a

It d a th

P

W actually a case of ‘Pointer to Pointer’. We were doing double dereferencing to access the elements of a two-dimensional array by using array name (a pointer) to access a row (another pointer) and further to access a column element (of ‘int’ data type).

I th to pointer or double dereference, the first poi pointer, which contains

address (^) value

ointers t

Si l I di i ( i l d f )

D bl I di i (d bl d f )

address address value

P

technique to avoid any problem. Earlier, we used arrays and pointers interchangeably. We can think that a pointer to pointer is like a pointer to a group of arrays because a pointer itself can be considered as an array. We can elaborate with the following example by declaring character strings. While using an array, we at first decide about the length of the array. For example, you are asked to calculate the average age of your class using the array. What would be the dimension of the array? Normally, you will look around, c the class and keep the same siz agood programmer, you will class in the future and decide to take the size of the array as 100. Here, you have taken care of the future requirements and made the program flexible. But the best thing could be: to get the size of the array from the user at runtime and set it in the program

docsity.com

ments

ntil now, we have always written the ‘main()’ function as under:

ut we are now in a position to write something inside the parenthesis of the ‘main()’ C language, whenever a program is executed, the user can provide the

e argument1 argument2 ……argumentN

we rom the command line just before executing the mechanism. In C, this can be done by using rgc’ and ‘argv’ arguments inside the main( ) function as:

‘main()’ function. However, you can give the desired names to them.

argc = rgv = It is a pointer to an array of character strings that contain the arguments, one er to pointer to char.

Command Line Argu

U

main( ) {

... // code statements } B function. In command-line arguments to it like:

C:\Dev-cpp\work>Program-nam

We have so far been taking input using the ‘cout’ and ‘cin’ in the program. But now can also pass arguments f program. For this purpose, we will need a ‘a

void main(int argc, char **argv) {

... }

Note that ‘argc’ and ‘argv’ are conventional names of the command line parameters of the

Number of command line arguments. Its type is ‘int’. a per string. ‘**argv’ can be read as point

docsity.com

argv

Now the command li argu ssed from inside the program using ‘argc’ and ‘argv’ vari les. I xperience for you to try out the following code:

command line arguments */ include

Program-name

Argument 1 Argument 2

Argument 3 0

ne ments can be acce ab t will be an interesting e

/* Accessing the

main(int argc, char **argv) { cout << argc << endl; cout << *argv; }

If we run this program without any argument, then what should be the answer. It will

c:\dev-cpp\work>program 1 program

be not correct to think that the argc (number of arguments) is zero as we have not passed any argument. It counts program name as the first argument. So programs written in C/C++ know their names supplied in the first command-line argument. By running the above program, we can have the following output:

Here we see that the number he program name itself. You have to go o the mand line arguments or you can discuss on the discus command line arguments.

e command line arguments are separated by spaces. You can provide command line arguments to a program as under:

of arguments is 1 with the first argument as t t command prompt to provide the com sion board, how to use Dev-C++ to pass

Th

c:\dev-cpp\work>program 1 2

Here the number of arguments (argc) will be 3. The argument “1” and “2” are available inside the program as character strings. Therefore, you have to convert them into integers to ensure their usage as as numbers.

docsity.com

option. Using command- ne arguments lends your program a very professional touch and facilitates the

ase Study: A Card Shuffling and Dealing Simulation pointer pointer mechanism.

deck of cards and to deal it out.

The are 4 uits in s 13 c ueen and King. A deck has 13 * 4 = 52 cards in total.

roblem Analysis, Design and Implementation: ent, we are dealing with the deck of cards, identified by its suit i.e. it may be one of the onds or Clubs. Also every card has one value in the range to King. So we want to identify them in our program and our use English like ‘five of Clubs’. We will declare one array of suit

*suite[4] = {“Hearts”, “Diamonds”, “Clubs”, “Spades” };

of values of cards: ce[13] = { “Ace”, “Deuce”, “Three”, “Four”, “Five”, “Six”, ”, “Nine”, “Ten”, “Jack”, “Queen” and “King”};

iced the use of array of pointers and ‘const’ keyword here. Both the n a way to avoid any wastage of space. Also notice the use of tants because we want to use these values em.

ck which has 52 cards. The deck is the one that is being shuffled it has some algorithmic requirements. be size and structure of the deck. It can either be linear array of uites and 13 values (faces) per suit. Logically, it makes sense to array of 4 suites and 13 faces per suit like: 3] = {0};

rms of Algorithm Analysis. with the 0 value, so that it holds no cards at start or it is distribute 52 cards. Who will load the ‘deck’ first, shuffle the

arguments are normally used to indicate a file name or an li program’s use in batch files.

C Now we want to move on to a real-world example where we can demonstrate to

Problem:

Write a program to randomly shuffle the

Some Facts of Card Games:

  • re s one deck: Hearts, Spades, Diamonds and Clubs.
  • Each suit ha ards: Ace, Deuce, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Q

P

As obvious from the problem statem required to be identified. A card is Hearts, Spades, Diam starting from Ace requirement is to like:

const char

The second array is const char *fa “Seven”, “Eight

You must have not arrays are declared i ‘const’ keyword. We declared arrays as cons without modifying th

Now we come to de and dealt. Definitely, Firstly, what should 52 elements or 4 s have two-dimensional int deck[4][

We will now think in te The ‘deck’ is initialized empty. We want to cards and deal them out. How to do it?

docsity.com

52 cards (a deck) randomly, therefore, we can think of a loop to ly in every iteration. We will randomly choose one out of the 4 lue out of 13 values and store the card with its card number y this way, we will be writing numbers in the two-dimensional domly. That functionality is part of ‘shuffle ()’ function.

int wDeck[][13] )

lumn, card;

card = 1; card <= 52; card++){ do{ row = rand() % 4; column = rand() % 13; } while( wDeck [ row ][ column ] != 0 ); wDeck[ row ][ column ] = card;

the ‘rand()’ function usage to generate random numbers. We are mly generated number by 4 and 13 to ensure that we get numbers ange. That is 0 to 3 for suites and 0 to 12 for values or faces. You n inside the ‘while statement, ‘wDeck[ row ][ column ] != 0 ‘. e don’t overwrite row and column, which has already been ccupied by some card.

Now we want to deal the deck. How to deal it? At first, search for card number 1 inside the deck, wherever it is found inside the ‘deck’ array, note down the row of this element. Use this row to get the name of the ‘suite’ array. Similarly use the column to take out the value of the card om the ‘face’ array.” See that the deal function is quite simple now.

1; card <= 52; card++ )

for( column = 0; column <= 12; column++) if( wDeck[ row ][ column ] == card ) cout << card << ". " < } while( wDeck [ row ][ column ] != 0 );

ow ][ column ] = card; }

Deck[][ 13 ], const char *wFace[], const char *wSuit[])

for ( card = 1; card <= 52; card++ )

for( column = 0; column <= 12; column++) if( wDeck[ row ][ column ] == card )

[row ] << '\n';

wDeck[ r

}

void deal( const int w { int card, row, column; const char *space;

for( row = 0; row <= 3; row++)

cout << card << ". " <

  1. Deuce of Hearts
  2. Ace of Spades
  3. Five of Diamonds
  4. Three of Hearts
  5. Six of Clubs
  6. Four of Hearts
  7. Ten of Spades
  8. Deuce of Spades
  9. Three of Diamonds
    1. Ace of Clubs
  10. Eight of Spades
  11. Nine of Hearts 4
  12. Four of Spades
  13. Queen of Diamonds 4 3. King of Clubs
  14. Five of Hearts
  15. Ace of Hearts
  16. Deuce of Diamonds
  17. Four of Diamonds
  18. Four of Clubs
  19. Six of Hearts
  20. Six of Spades
  21. King of Spades
  22. Nine of Diamonds

Exercises

  1. Write the program ‘tail’, which prints the last n lines of its input. By default, n is

ptional argument, so that

ips

Pointers and arrays are closely related in C. The array names can be used as ers but only as constant pointers.

A f ing a multi-dimensional array as a parameter must minimally def he leftmost one.

 e er is incremented, it points to the memory location of the next ent of o-dimensional array, if you add some

let’s say, but it can be changed by an o tail -n prints the last n lines.

T

point

 unction receiv ine all dimensions except t

Each tim a point elem its base type but in case of tw

docsity.com