







Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!








Deitel &
ded. In today’s cture, we will discuss pointers, the relationship between pointers and arrays, pointer
t means that we have attached a symbolic name x, at some x = 10 which replaces the value at that memory with 10. Similarly while talking about arrays, suppose an array as int y[10]. is means that we have reserved memory spaces for ten integers and named it collect is? ' y' represents the memory address of the beginning of this collective memory space. The first element of the array can be accessed as y[0]. 0 in C language, so the me The name of the array is a constant pointer which contains the memory ent of the array”
The di constan the array name will always point to the start of the array. In other words, it always contains the memory address of the first element of
Deitel - C++ How to Program Chapter 5 5.7, 5.
Pointer Express
Pointer, String and Arrays
Tips
In the previous lecture, we had just started the discussion on the topic of pointers. This topic is little complicated, yet the power we get with the pointers is very interesting. We can do many interesting things with pointers. When other languages like Java evolve with the passage of time, pointers are explicitly exclu le expressions, arithmetic with pointers, relationship between arrays and pointer, strings etc.
When we write int x, i memory location. Now we can use location Th ively as y. Now we will see what actually y
Remember arrays index starts from mory address of first element i.e. y[0] is stored in y. “ address of the first elem
ff erence between this and an ordinary pointer is that the array name is a t pointer. It means that
e array and cannot be reassigned any other address. Let's elaborate the point with
ay y of ten integers and a pointer to an emory address of an integer.
of y i.e. the address of the first element of wo things pointing to the same place, y nd yptr. Both are pointing to the first element of the array. However, y is a constant ointer and always points to the same location whereas yptr is a pointer variable that
hmetic uppose we have an array y and yptr , a pointer to array. We can manipulate arrays o access the fourth element of the array using y, we can say [3]; with yptr, we can write as *(yptr + 4). Now we have to see what happens when ment or add something to a pointer. We know that y is a constant pointer and can not be incremented_._ We can write y[0], y[1] etc. On the other hand, yptr is a ointer nd can be written as the statement yptr = y. It means that yptr e first element of the array. However, when we say yptr++, e value of ypt r is incremented. But how much? To explain it further, we increment a ormal iable like x++. If x contains 10, it will be incremented by 1 and ecome 11. The increment of a pointer depends on its data type. The data type, the se, yptr is an integer ointer ext integer in the emory. If an integer occupies four bytes in the memory, then the yptr++; will This can be understood from the following example.
ented address.
clude<iostream.h>
ain()
int y[10]; // an array of 10 integers ter the start of array address to pointer
emory address cout << “The memory address of yptr = “ << yptr << endl ; yptr++; // incrementing the pointer
th the help of following example.
int y[10]; int *yptr;
In the above statements, we declare an arr integer i.e. yptr. This pointer may contain a m
yptr = y;
This is an assignment statement. The value the array is assigned to yptr. Now we have t a p can also point to any other memory address.
Pointer Expressions and Arit S with both y and yptr. T y we incre it p variable a contains the address of th th n integer var b pointer points to, determines the amount of increment. In this ca p. Therefore, when we increment the yptr, it points to the n m increment its value by four.
// This program will print the memory address of a pointer and its increm
#in
m {
int *yptr; // an integer poin yptr = y; // assigning
// printing the m
// printing the incremented memory address cout << “The memory address after incrementing yptr = ” << yptr << endl; }
docsity.com
int *yptr;
yptr = y; // Assigning the address of first element of array.
cout << “Accessing 6 element of array as y[5] = ” << y[5] << endl;
cout << “Accessing 6th^ element of array as *(yptr + 5) = ” << *(yptr + 5) << endl;
cout << “Accessing 6th^ element of array as yptr[5] = “ << yptr[5] << endl;
#include <iostream.h>
main () { int y[10] = {0,5,10,15,20,25,30,35,40,45};
th
Th e output of the progr am is:
ccessing 6th element of array as y[5] = 25
cessing 6th element of array as yptr[5] = 25
Accessing 6th element of array as *(yptr + 5) = 25 Ac
In the above example, there are two new expressions i.e. *(yptr+5) and yptr[5]. In the atement *(yptr+5) , yptr is incremented first by 5 (parenthesis are must here). s to the 6th^ element of the array. The dereference pointer gives the alue at that address. As yptr is a pointer to an integer, so it can be used as array ame. So the expression yptr[5] gives us the 6th^ element of the array.
yptr = y; // Assigning the address of first element of array.
for (i = 0; i < 10 ; i ++) { cout << “\n The value of the element at position ” << i << “ is “ << *yptr; yptr ++ ; } }
st Resultantly, it point v n
The following example can explain how we can step through an entire array using pointer.
/* This program steps through an array using pointer */
#include <iostream.h>
main () { int y[10] = {10,20,30,40,50,60,70,80,90,100}; int *yptr, i;
docsity.com
The output of the program is:
The value of the element at position 0 is 10 The value of the element at position 1 is 20 The value of the element at position 2 is 30 The value of the element at position 3 is 40 The value of the element at position 4 is 50 The value of the element at position 5 is 60 The value of the element at position 6 is 70 The value of the element at position 7 is 80 The value of the element at position 8 is 90 The value of the element at position 9 is 100
Consider another example to elaborate the pointer arithmetic.
/* Program using pointer arithmetic */
#include <iostream.h>
main() { int x =10; int *yptr;
yptr = &x;
cout << “The address yptr points to = ” << yptr << endl ; cout << “The contents yptr points to = ” << *yptr << endl;
(*yptr) ++;
cout << “After increment, the contents are ” << *yptr << endl; cout << “The value of x is = ” << x << endl; }
The output of the program is:
The address yptr points to = 0x22ff7c The contents yptr points to = 10 tents are 11 he value of x is = 11
After increment, the con T
Here the statement (*yptr) ++ is read as “increment whatever yptr points to”. This the value of the variable. As yptr and x both are pointing to the same nsider the statement *yptr + 3 ; his is on and there is no assignment so the value of x will not be changed
will increment location, the contents at that location becomes 11. Co T an expressi
docsity.com
we can. Suppose we have two pointers pointing to the same memory address. When e subtract these, the answer will be zero. Similarly, if a pointer is pointing to the
int y[10], *yptr1, *yptr2;
yptr1 = &y[0];
w first element of an integer array while another pointer pointing to the second element of the array. We can subtract the first pointer from second one. Here the answer will be one, i.e. how many array elements are these two pointers apart.
Consider the following sample program:
/* Program using the pointer subtraction */
#include <iostream.h>
main () {
yptr2 = &y[3];
cout << “ The difference = “ << yptr2 - yptr1;
The ou
nce = 3
tput of the program is:
The differe
In the above program, we have taken two integer pointers yptr1 and yptr2 and an the first element of e array while yptr2 is pointing to the 4th^ element of the array. The difference ters can be shown by using cout statement. Here the result ould be twelve. But the program will show the result as three. When we increment r pointer by 1, we have seen that the address is changed by four. When we tract pointers, it tells us the distance between the two elements that the pointers y elements are between these two pointers. As nd the yptr2 is pointing to y[3] , so the answer is three. In way, it tells how many units of data type (pointers data type) are between the two ointer it ter subtraction is allowed as it et are the same as the data pe of the pointer.
mem
integer array y[10]. The pointer yptr1 is pointing to the address of th between these two poin sh an intege sub pointed to. It will tell us how many arra the yptr1 is pointing to y[0] a a p s. Pointer add ion is not allowed, however, poin gives the distance b ween the two pointers in units, which ty
A ory image of an array with a pointer.
docsity.com
cin >> x ;
This diagram shows how an array occupies space in the memory. Suppose, we have an integer array named y and yptr is a pointer to an integer and is assigned the address of the first element of the array. As this is an integer array, so the difference between each element of the array is of four bytes. When the yptr is incremented, it starts pointing to the next element in the array.
Pointer Comparison
We have seen pointers in different expressions and arithmetic operations. Can we compare pointers? Yes, two pointers can be compared. Pointers can be used in conditional statements as usual variables. All the comparison operators can be used with pointers i.e. less than, greater than, equal to, etc. Suppose in sorting an array we are using two pointers. To test which pointer is at higher address, we can compare them and take decision depending on the result.
Again consider the two pointers to integer i.e. yptr1 and yptr2. Can we compare *yptr1 and *yptr2? Obviously *yptr1 and *yptr2 are simple values. It is the value of integer yptr1 , yptr2 points to. When we say *yptr1 > *yptr2, this is a comparison of simple two integer values. Whenever we are using the dereference pointer (pointers with *), all normal arithmetic and manipulation is valid. Whenever we are using pointers themselves, then certain type of operations are allowed and restrictions on other. Make a list what can we do with a pointer and what we cannot.
Consider a sample program as follows:
/* Program using the dereference pointer comparison */
#include <iostream.h>
main () { int x, y, *xptr, *yptr;
cout << “ \n Please enter the value of x = “ ;
yptr
y[0] y[1] y[2] y[3] y[4]
Addresses :^3000 3004 3008 3012
yptr++ yptr
docsity.com
name[4] = ‘\0’ ;
ase. Whenever ack slash ( \ ) is used, the compiler considers both the characters as single (also known as escape characters). So ‘\n’ is new line character, ‘\t’ a tab character and ‘\0’ a null character. All of these are considered as single characters. What is the benefit of having this null character at the end of the string? Write a program, do not use the null character in the string and try to print the character array using cout and see what happens? cout uses the null character as the string terminating point. So if cout does not find the null character it will keep on printing. Remember, if we want to store fifteen characters in an array, the array size should be at least sixteen i.e. fifteen for the data and one for the null character. Do we always need to write the null character at the end of the char array by ourselves? Not always, there is a short hand provided in C, i.e. while declaring we can initialize the arrays as:
char name[20] = “Amir”;
When we use double quotes to initialize the character array, the compiler appends null character at the end of the string. “Arrays must be at least one character space larger than the number of printable characters which are to be stored”
Example: Write a program which copies a character array into given array.
Solution:
Here is the complete code of the program:
/* This program copies a character array into a given array */
#include <iostream.h>
main( ) { char strA[80] = "A test string"; char strB[80];
char ptrA; / a pointer to type character */ char ptrB; / another pointer to type character */
ptrA = strA; /* point ptrA at string A / ptrB = strB; / point ptrB at string B */
while(*ptrA != '\0') { *ptrB++ = *ptrA++; // copying character by character }
*ptrB = '\0';
Here we are using two characters in single quotes. But it is a special c b
docsity.com
cout << “String in strA = ” << strA << endl; /* show strA on screen / cout << “Stringin strB = ” << strB << endl; / show strB on screen */ }
The output of the program is:
String in strB = A test string
String in strA = A test string
Explanation:
have declared a char array named strA of size 80 and initialized it with some value say “A test String” using the double quotes. Here we don’t need to put a null ch ter. insert it. But while declaring another array strB of two char pointers * ptrA and * ptrB. The objective of th rray into another array. We have assigned the star g add d strB to ptrB. Now we have to run a loop to copy all the characters from one array to other. To terminate the loop, we have to know about the actual number of characters or have to use the string termination haracter. As we know, null character is used to terminate a string, so we are using the ondition in 'while loop' as: *ptrA != ‘\0’ , simply checking that whatever ptrA is ointing to is not equal to ‘\0’. Look at the statement *ptrB++ = *ptrA++. What has t of all, whatever ptrA is pointing to will be assigned
ll be copied to the rst character of strB. Afterwards, the pointers will be incremented, not the values they ar pointing to the 2nd^ element of the array strA nd ptrB is pointing to the 2 element of the array strB. In the 2nd^ repetition, the loop
strA are copied to array strB. Is this program complete? No, e array strB is not containing the null character at the end of the string. Therefore, we hav cter to strB. Do we need to increment the rray pointer? No, simply due to the fact that in the assignment statement ( *ptrA++ = ptrB++;), the pointers are incremented after the assignment. This program now uccessfully copies one string to other using only pointers. We can also write a nction for the string copy. The prototype of the function will be as:
void myStringCopy (char *destination, const char *source) ;
his function takes two arguments. The first one is a pointer to a char while second rgument is a const pointer to char. The destination array will be changed and all the haracters from source array are copied to destination. At the same time, we do not ed the keyword const
Suppose, we
arac The compiler will automatically the same size, we declare is exercise is to copy one a tin ress of array strA to ptrA an
c c p happened in this statement? Firs to the location where ptrB is pointing to. When the loop starts, these pointers are pointing to the start of the array. So the first character of strA wi fi e pointing to. Therefore, ptrA is a nd condition will be tested. If ptrA is not pointing to a null character the assignment for the 2nd^ element of the array takes place and so on till the null character is reached. So all the characters of array th e explicitly assigned the null chara a
s fu
a c want that the contents of source should be changed. So we us with it. The keyword const makes it read only and it can not be changed accidentally.
docsity.com
number of bytes occupied by the data type that the pointer points to Use key word const with pointers to avoid unwanted changes The name of array is a constant pointer. It cannot be reassigned
docsity.com