Chapter 7 Pointers and C-Strings
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
1
What is a Pointer?
•Pointer variables, simply called pointers, are designed to hold
memory addresses as their values.
•Normally, a variable contains a specific value, e.g., an integer, a
floating-point value, and a character. However, a pointer contains the
memory address of a variable that in turn contains a specific value.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
2
Declare a Pointer
Like any other variables, pointers must be declared before they can
be used. To declare a pointer, use the following syntax:
dataType *pVarName;
Each variable being declared as a pointer must be preceded by an
asterisk (*). For example, the following statement declares a pointer
variable named pCount that can point to an int varaible.
int *pCount, count;
Count=5;
pCount=&count;
// & is the address operator.
TestPointer.cpp
pCount
Address of
pCount
count
Run
Address of variable count
Address of variable count
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
5
3
#include <iostream>
using namespace std;
int main()
{
int count = 5;
int *pCount = &count;
TestPointer.cpp
cout << "The address of count is " << &count << endl;
cout << "The address of count is " << pCount << endl;
cout << "The value of count is " << count << endl;
cout << "The value of count is " << *pCount << endl;
return 0;
}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
4
Dereferencing
Referencing a value through a pointer is called indirection
(dereferencing). The syntax for referencing a value from a
pointer is
*pointer
For example, you can increase count using
count++; // direct reference
or
(*pCount)++; // indirect reference
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
5
Pointer Type
A pointer variable is declared with a type such as int, double, etc.
You have to assign the address of the variable of the same type. It is
a syntax error if the type of the variable does not match the type of
the pointer. For example, the following code is wrong.
int area = 1;
double *pArea = &area; //
Wrong
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
6
Initializing Pointer
Like a local variable, a local pointer is assigned an arbitrary value
if you don’t initialize it.
A pointer may be initialized to 0, which is a special value for a
pointer to indicate that the pointer points to nothing.
You should always initialize pointers to prevent errors.
Dereferencing a pointer that is not initialized could cause fatal
runtime error or it could accidentally modify important data.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
7
Caution
You can declare two variables on the same line. For example, the
following line declares two int variables:
int i = 0, j = 1;
Can you declare two pointer variables on the same line as follows?
int* pI, pJ;
No, this line is equivalent to:
You have to put:
int *pI, pJ;
int *pI, *pJ;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
8
Passing Arguments by Reference
with Pointers
There are three ways to pass arguments to a
function in C++:
pass by value,
pass by reference with reference arguments
pass by reference with pointers.
TestPointerArgument.cpp
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
9
#include <iostream>
using namespace std;
TestPointerArgument.cpp
// Swap two variables
void swap(int *pValue1, int *pValue2)
{
// Swap n1 with n2
int temp = *pValue1;
*pValue1 = *pValue2;
*pValue2 = temp;
}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
10
int main()
{
// Declare and initialize variables
int num1 = 1;
int num2 = 2;
cout << "Before invoking the swap function, num1 is "
<< num1 << " and num2 is " << num2 << endl;
// Invoke the swap function to attempt to swap two variables
swap(&num1, &num2);
cout << "After invoking the swap function, num1 is " << num1 <<
" and num2 is " << num2 << endl;
return 0;
}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
11
Arrays and Pointers
Recall that an array variable without a bracket and a subscript
actually represents the starting address of the array. In this sense, an
array variable is essentially a pointer. Suppose you declare an array
of int value as follows:
int list[6] = {11, 12, 13, 14, 15, 16};
list
list+1
list+2
list+3
list+4
list+5
11
12
13
14
15
16
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
12
Array Pointer
*(list + 1) is different from *list + 1. The
dereference operator (*) has precedence over +.
So, *list + 1 adds 1 to the value of the first element
in the array, while *(list + 1) dereference the
element at address (list + 1) in the array.
ArrayPointer.cpp
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
13
#include <iostream>
using namespace std;
int main()
{
int list[6] = {11, 12, 13, 14, 15, 16};
ArrayPointer.cpp
for (int i = 0; i < 6; i++)
cout << "address: " << (list + i) <<
" value: " << *(list + i) << " " <<
" value: " << list[i] << endl;
list[i] is equivalent to *(list+i)
return 0;
}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
14
Using const with Pointers
You learned how to declare a constant using the const
keyword. A constant cannot be changed once it is
declared. You can declare a constant pointer. For example,
see the following code:
double radius = 5;
double * const pValue = &radius;
const double * const pValue=&radius; // pointer is a constant
and data pointed by the pointer is also a constant.
Constant data
Constant pointer
const double * const pValue = &radius;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
15
Using const with Pointers
double radius=5;
double * const pValue=&radius;
double length = 5;
*pValue=6; //OK
pValue=&length; // Wrong because pValue is a constant pointer.
const double *pValue1=&radius;
*pValue=6; //Wrong because pValue1 points to constant data.
pValue1=&length; //OK
const double * const pValue2=&radius;
*pValu2=6; //Wrong because pValue2 points to a constant data
*pValue2=&length; //Wrong because pValue2 is a constant pointer
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
16
ConstParameter.cpp
#include <iostream>
using namespace std;
void printArray(const int *, const int); // function prototype
int main()
{
int list[6] = {11, 12, 13, 14, 15, 16};
printArray(list, 6);
return 0;
}
void printArray(const int * list, const int size)
{
for (int i = 0; i < size; i++)
cout << list[i] << " ";
}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
Characters and C-Strings
Strings are used often in programming. You have
used string literals. A string is a sequence of
characters. There are two ways to process strings
in C++. One way is to treat strings as arrays of
characters. This is known as pointer-based strings
or C-strings. The other way is to process strings
using the string class. The string class will be
introduced in §9.14. This section introduces
pointer-based strings.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
18
Character Test Functions
Function
Description
Example
isdigit(c)
Returns true if c is a digit.
isdigit('7') is true
isdigit('a') is false
isalpha(c)
Returns true if c is a letter.
isalpha('7') is false
isalpha('a') is true
isalnum(c)
islower(c)
isupper(c)
isspace(c)
isprint(c)
isgraph(c)
ispunct(c)
iscntrl(c)
Returns true if c is a letter or
isalnum('7') is true
a digit.
isalnum('a') is true
Returns true if c is a lowercase
islower('7') is false
letter.
islower('a') is true
Returns true if c is an uppercase
isupper('a') is false
letter.
isupper('A') is true
Returns true if c is a whitespace
isspace('\t') is true
character.
isspace('A') is false
Returns true if c is a printable
isprint(' ') is true
character including space ‘ ‘.
isprint('A') is true
Returns true if c is a printable
isgraph(' ') is false
character excluding space ‘ ‘.
isgraph('A') is true
Returns true if c is a printable
ispunct('*') is true
character other than a digit,
ispunct(',') is true
letter, or space.
ispunct('A') is false
Returns true if c is a control
iscntrl('*') is false
character such as '\n', '\f', '\v',
iscntrl('\n') is true
'\a', and '\b'.
iscntrl('\f') is true
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
19
Case Conversion Functions
Function
Description
Example
tolower(c)
Returns the lowercase equivalent of
tolower('A') returns 'a'
c, if c is an uppercase letter.
tolower('a') returns 'a'
Otherwise, return c itself.
tolower('\t') returns '\t'
Returns the uppercase equivalent of
toupper('A') returns 'A'
c, if c is a lowercase letter.
toupper('a') returns 'A'
Otherwise, return c itself.
toupper('\t') returns '\t'
toupper(c)
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
20
#include <iostream>
CharacterFunctions.cpp
using namespace std;
int main()
{
cout << "Enter a character: ";
char ch;
cin >> ch;
cout << "You entered " << ch << endl;
if (islower(ch)) {
cout << "It is a lowercase letter " << endl;
cout << "Its equivalent uppercase letter is " <<
static_cast<char>(toupper(ch)) << endl; }
else if (isupper(ch)) {
cout << "It is an uppercase letter " << endl;
cout << "Its equivalent lowercase letter is " <<
static_cast<char>(tolower(ch)) << endl;
}
else if (isdigit(ch)) {
cout << "It is a digit character " << endl;
}
(c) 2007 Pearson Education, Inc. All rights reserved.
21
return 0;} Liang, Introduction to C++ Programming,013225445X
CharacterFunctions.cpp
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
22
Storing and Accessing Strings
A pointer-based string in C++ is an array of characters
ending in the null terminator ('\0'), which indicates where
a string terminates in memory. An array can be accessed
via a pointer. So a string can also be accessed via a
pointer, which points to the first character in the string. So
you can declare a string variable using an array or a
pointer. For example, the following two declarations are
both fine:
char city[7] = "Dallas"; // Option 1
char *pCity = "Dallas"; // Option 2
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
23
Pointer Syntax
char city[7] = "Dallas"; // Option 1
char *pCity = "Dallas"; // Option 2
You can access city or pCity using the array syntax or
pointer syntax. For example,
cout << city[1] << endl;
cout << *(city + 1) << endl;
cout << pCity[1] << endl;
cout << *(pCity + 1) << endl;
each displays character a (the second element in the
string).
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
24
Reading Strings
You can read a string from the keyboard using the
cin object. For example, see the following code:
cout << "Enter a city: ";
cin >> city; // read to array city
cout << "You entered " << city << endl;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
25
Reading Strings Using getline
C++ provides the cin.getline function in the iostream
header file, which reads a string into an array. The syntax
of the function is:
cin.getline(char array[], int size, char delimitChar)
The function stops reading characters when the delimiter
character is encountered or when the size - 1 number of
characters are read. The last character in the array is
reserved for the null terminator ('\0'). If the delimiter is
encountered, it is read, but not stored in the array. The
third argument delimitChar has a default value ('\n').
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
26
String Functions
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
27
String Functions
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
28
#include <iostream>
#include <cstring>
using namespace std;
CopyString.cpp
int main()
{
char s1[20];
char s2[20] = "Dallas, Texas";
char s3[20] = "AAAAAAAAAA";
strcpy(s1, s2);
strncpy(s3, s2, 6);
s3[6] = '\0'; // Insert null terminator
cout << "The string in s1 is " << s1 << endl;
cout << "The string in s2 is " << s2 << endl;
cout << "The string in s3 is " << s3 << endl;
cout << "The length of string s3 is " << strlen(s3) << endl;
return 0;}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
29
#include <iostream>
#include <cstring>
using namespace std;
CompareString.cpp
int main()
{
char *s1 = "abcdefg";
char *s2 = "abcdg";
char *s3 = "abcdg";
cout << "strcmp(s1, s2) is " << strcmp(s1, s2) << endl;
cout << "strcmp(s2, s1) is " << strcmp(s2, s1) << endl;
cout << "strcmp(s2, s3) is " << strcmp(s2, s3) << endl;
cout << "strncmp(s1, s2, 3) is " << strncmp(s1, s2, 3) << endl;
return 0;
}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
30
#include <iostream>
CombineString.cpp
#include <cstring>
using namespace std;
int main() {
char s1[20] = "Dallas";
char s2[20] = "Texas, USA";
char s3[20] = "Dallas";
strcat(strcat(s1, ", "), s2);
strncat(strcat(s3, ", "), s2, 5);
cout << "The string in s1 is " << s1 << endl;
cout << "The string in s2 is " << s2 << endl;
cout << "The string in s3 is " << s3 << endl;
cout << "The length of string s1 is " << strlen(s1) << endl;
cout << "The length of string s3 is " << strlen(s3) << endl;
return 0;
}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
31
Checking Palindromes
A string is a palindrome if it reads the same
forward and backward. The words “mom,” “dad,”
and “noon,” for example, are all palindromes.
CheckPalindrome.cpp
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
32
#include <iostream>
#include <cstring>
using namespace std;
// Check if a string is a palindrome
bool isPalindrome(const char *);
int main()
{
// Prompt the user to enter a string
cout << "Enter a string: ";
char s[80];
cin.getline(s, 80);
if (isPalindrome(s))
cout << s << " is a palindrome" << endl;
else
cout << s << " is not a palindrome" << endl;
return 0;
}
bool isPalindrome(const char * const s)
{
// The index of the first character in
the string
int low = 0;
// The index of the last character in
the string
int high = strlen(s) - 1;
while (low < high)
{
if (s[low] != s[high])
return false; // Not a palindrome
low++;
high--;
}
return true; // The string is a
palindrome
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
}
33
013225445X
© Copyright 2026 Paperzz