// archives

Array

This tag is associated with 7 posts

Functions Using Array Ranges

C++ functions that process arrays need to be informed about

The kind of data in the array
The location of the beginning of the array
And the number of elements in the array

The traditional C/C++ approach to functions that process arrays

Is to pass a pointer to the start of the array as one argument

And to pass the size [...]

More Array Function Examples

When you choose to use an array to represent data, you are making a design decision

But design decisions should go beyond how data is stored; they should also involve how the data is used

Often, you’ll find it profitable to write specific functions to handle specific data operations

(The profits here include increased program reliability, ease of [...]

The Implications of Using Arrays as Arguments

Let’s look at the implications of (A-1)

The function call sum_arr(cookies, ArSize)

Passes the address of the first element of the cookies array and the number of elements of the array to the sum_arr() function

The sum_arr() function

Assigns the cookies address to the pointer variable arr and assigns ArSize to the int variable n

This means (A-1) doesn’t really [...]

Strings

A string

Is a series of characters stored in consecutive bytes of memory

C++ has two ways of dealing with strings

The first, taken from C and often called a C-style string, is the first one this page examines
Later, we will discuss an alternative method based on a string class library

The idea of a series of characters stored [...]

Introducing the string Class

The ISO/ANSI C++ Standard

Expanded the C++ library by adding a string class (B-1)
(B-2) So now, instead of using a character array to hold a string, you can use a type string variable (or object, to use C++ terminology) (B-3)
(B-3) As you’ll see, the string class is simpler to use than the array and also provides [...]

Adventures in String Input

(A-1) shows that string input

Can be tricky

Example of (A-1)

// instr1.cpp — reading more than one string
#include <iostream>
int main()
{
using namespace std;
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];
 
cout << "Enter your name:\n";
cin >> name;
cout << "Enter your favorite dessert:\n";
cin >> dessert;
cout << "I have some delicious " << dessert;
cout << " for you, " << name << [...]

Using Strings in an Array

The two most common ways of getting a string into an array

Are to initialize an array to a string constant and to read keyboard or file input into an array
(A-1) demonstrates these approaches by initializing one array to a quoted string and using cin to place an input string in a second array

The program (A-1) [...]