Home>

C++ strings and pointers

There are three ways to access a string in C++ (the first two methods were introduced in Chapter 5).

Store a string in a character array

[Example] Define a character array and initialize it,Then output the string in it.

#include<iostream>
using namespace std;
int main ()
{
  char str []="i love china!";
  cout<str<endl;
  return 0;
}

Runtime output:

i love china!

Use string variables to store strings

[Example] Define a string variable and initialize it.Then output the string in it.

#include<string>
#include<iostream>
using namespace std;
int main ()
{
  string str="i love china!";
  cout<str<endl;
  return 0;
}

Point to a string with a character pointer

[Example] Define a character pointer variable and initialize it.Then print the string it points to.

#include<iostream>
using namespace std;
int main ()
{
  char * str="i love china!";
  cout<str<endl;
  return 0;
}

Access to characters in a string,You can use the subscript method,You can also use the pointer method.

[Example] Copy string str1 to string str2.

Define two character arrays str1 and str2, and set two pointer variables p1 and p2 to point to relevant characters in the two character arraysBy changing the value of pointer variables so that they point to different characters in the string,To achieve character copy.

#include<iostream>
using namespace std;
int main ()
{
  char str1 []="i love china!", str2 [20], * p1, * p2;
  p1=str1;p2=str2;
  for (;* p1!="\\ 0";p1 ++, p2 ++)
    * p2=* p1;
  * p2="\\ 0";
  p1=str1;p2=str2;
  cout<"str1 is:"<p1<endl;
  cout<"str2 is:"<p2<endl;
  return 0;
}

The result is:

str1 is:i love china!
str2 is:i love china!

This example illustrates how to use character pointers.In fact, for Example 6.13, the string variable is very simple to handle:

 string str1="i love china!", str2;//define string variable
  str2=str1;//Copy str1 to str2

C++ arrays and pointers

Pointer to array element

A variable has an address,An array contains several elements,Each array element occupies a storage unit in memory,They all have corresponding addresses.Since pointer variables can point to variables,Of course, you can also point to array elements (put the address of an element into a pointer variable). The so-called array element pointer is the address of the array element.

 int a [10];//Define an integer array a, which has 10 elements
  int * p;//Define a pointer variable p whose base type is integer
  p=& a [0];//Assign the address of element a [0] to the pointer variable p, so that p points to a [0]

In C++, the array name represents the address of the first element in the array (that is, the element with the serial number 0). Therefore, the following two statements are equivalent:

 p =&a [0];
  p=a;

You can assign an initial value to a pointer variable when you define it:

 int * p =&a [0];//The initial value of p is the address of a [0]

Can also be written as

 int * p=a;//Same as the previous line

Array elements can be referenced by pointers.Suppose p has been defined as a pointer variable whose base type is integer.And has given it the address of an integer array element,Make it point to an array element.If there are the following assignment statements:

 * p=1;//Assign a value of 1 to the array element currently pointed to by p

If the pointer variable p already points to an element in the array,Then p + 1 points to the next element in the same array.

If the initial value of p is&a [0], then:

1) p + i and a + i are the addresses of a [i], or they point to the i-th element of the a array, see Figure 6.12.

2) * (p + i) or * (a + i) is the array element pointed to by p + i or a + i,That is a [i].

As can be seen,[] Is actually an indexing operator.The solution of a [i] is:first calculate the address of the array element by a + i × d,Then find the value in the cell pointed to by this address.

3) pointer variables to array elements can also be subscripted,For example, p [i] is equivalent to * (p + i).

According to the above description,Reference an array element,The following methods are available:

Subscript method, such as a [i] form;

Pointer method, such as * (a + i) or * (p + i). Where a is the array name,p is a pointer variable to an array element.If the value of p has been made a, * (p + i) is a [i]. The desired element can be found with a pointer to an array element.Using pointer method can make the target program high quality.

[Example] Output all elements in the array.Suppose there is an integer array a with 10 elements. There are 3 ways to output the value of each element:

1) Subscript method.

#include<iostream>
using namespace std;
int main ()
{
  int a [10];
  int i;
  for (i=0;i<10;i ++)
  cin>>a [i];//Refer to array element a [i]
  cout<endl;
  for (i=0;i<10;i ++)
   cout<a [i]<"""//Reference array element a [i]
  cout<endl;
  return 0;
}

The operation is as follows:

9 8 7 6 5 4 3 2 1 0↙ (enter the value of 10 elements)
9 8 7 6 5 4 3 2 1 0 (output value of 10 elements)

2) Pointer method.

Change "a [i]" in lines 7 and 10 of the above program to "* (a + i)", the operation is the same as (1).

3) Pointer variable to the array element.

#include<iostream>
using namespace std;
int main ()
{
  int a [10];
  int i, * p=a;//The pointer variable p points to the first element a [0] of the array a
  for (i=0;i<10;i ++)
    cin>>* (p + i);//Enter a [0] ~ a [9] for a total of 10 elements
  cout<endl;
  for (p=a;p<(a + 10);p ++)
    cout<<* p<<"""
  cout<endl;
  return 0;
}

The operation is the same as before.Please analyze the change of p value and the value of * p carefully.

Comparison of 3 methods:

The execution efficiency of methods (1) and (2) is the same.Method (3) is faster than methods (1) and (2). This method can improve execution efficiency.

It is more intuitive to use the subscript method,Can know directly the first few elements.The methods of address method or pointer variable are not very intuitive,It is difficult to quickly determine which element is currently being processed.Note that when using pointer variables to point to array elements:The pointer variable p can point to a valid array element,In fact, it can also point to the memory unit after the array.If there is

 int a [10], * p=a;//The initial value of the pointer variable p is&a [0]
  cout<<* (p + 10);//To output the value of a [10]

When using pointer variables to point to array elements,Be sure to point to valid elements in the array.

The operation of pointers to array elements is more flexible.Be careful.Here are a few examples.

If we first point p to the first element of the array a (that is, p=a), then:

1) p ++ (or p +=1). Make p point to the next element,That is a [1]. If you use * p, get the value of the next element a [1].

2) * p ++. Since ++ and * have the same priority,The combination direction is from right to left,It is therefore equivalent to * (p ++). The effect is:first get the value of the variable pointed to by p (ie * p), and then increase the value of p by 1. The last for statement in Example 6.5 (3):

 for (p=a;p<a + 10;p ++)
  cout<<* p;

Can be rewritten as

 for (p=a;p<a + 10;)
  cout<<* p ++;

3) * (p ++) and * (++ p) have different functions.The former takes the value of * p first, and then increments p by one. In the latter case, p is incremented by 1 and then * p is taken. If the initial value of p is a (that is,&a [0]), output * (p ++) to get the value of a [0], and output * (++ p) to get the value of a [1].

4) (* p) ++ means the value of the element pointed to by p is increased by 1, that is, (a [0]) ++. If a [0]=3, then the value of (a [0]) ++ is 4. Note:It is the element value plus one, not the pointer value plus one.

5) If p currently points to a [i], then

* (p--) First perform "*" operation on p to get a [i], then decrement p by 1, and p points to a [i-1].

* (++ p) First increment p by 1 and then perform * operation to get a [i + 1].

* (-p) decrements p by 1, and then performs * to obtain a [i-1].

The ++ and-operators are useful for pointer variables to array elements,You can make pointer variables move forward or backward automatically,Point to the next or previous array element.For example, to output 100 elements of the a array, you can use the following statement:

 p=a;
  while (p<a + 100)
  cout<<* p ++;

or

 p=a;
  while (p<a + 100)
  {
    cout<<* p;
    p ++;
  }

When using * p ++ operations,It's easy to get wrong,Be very careful,Find out whether to take p first or increment p first.

Using pointer variables as function parameters to receive array addresses

As mentioned earlier, you can use array names as function parameters.As mentioned earlier, the array name represents the address of the first element of the array.Use the array name as a function parameter,Passed is the address of the first element of the array.It is easy to imagine:using pointer variables as function parameters,It can also receive the address of the first element of the array passed from the argument (in this case, the argument is the name of the array). The following uses pointer variables as function parameters.

[Example] Arrange 10 integers in ascending order.Based on the procedure of Example 5.7,Change the parameter to a pointer variable.

#include<iostream>
using namespace std;
int main ()
{
  void select_sort (int * p, int n);//function declaration
  int a [10], i;
  cout<"enter the originl array:"<endl;
  for (i=0;i<10;i ++) //Enter 10 numbers
    cin>>a [i];
  cout<endl;
  select_sort (a, 10);//function call,Array name as argument
  cout<"the sorted array:"<endl;
  for (i=0;i<10;i ++) //Output 10 sorted numbers
    cout<a [i]<<""
  cout<endl;
  return 0;
}
void select_sort (int * p, int n) //Use pointer variables as formal parameters
{
  int i, j, k, t;
  for (i=0;i<n-1;i ++)
  {
    k=i;
    for (j=i + 1;j<n;j ++)
      if (* (p + j)<* (p + k)) k=j;//Access array elements by pointer method
    t=* (p + k);* (p + k)=* (p + i);* (p + i)=t;
  }
}

Operation

The c++ compilation system always treats the parameter group name as a pointer variable.

In fact, there is no parameter group occupying storage space when the function is called.Only pointer variables.

Participate in the combination of formal parameters,There are four forms:

Argument

Array name array name

Array name pointer variable

Pointer variable array name

Pointer variable pointer variable

on the basis of,One more problem:the real parameter group name a represents a fixed address,Or pointer constants,It is therefore impossible to change the value of a.Such as:

 a ++;//Syntax error,a is a constant and cannot be changed

The formal parameter group name is a pointer variable,It is not a fixed address value.Its value can be changed.At the beginning of the function call,It receives the address of the first element of the real parameter group,But during function execution,It can be assigned again.Such as:

f (array [], int n)
{
  cout<array;//output the value of array [0]
  array=array + 3;//The value of the pointer variable array has changed,Point to array [3]
  cout<<* arr<endl;//output the value of array [3]
}

Multidimensional arrays and pointers

Pointer variables can point to elements in a one-dimensional array,Can also point to elements in a multidimensional array.

1) The address of a multidimensional array element

There is a two-dimensional array a, which has 3 rows and 4 columns. It is defined as:

 int a [3] [4]={{1,3,5,7}, {9,11,13,15}, {17,18,21,23}};

a is an array name.The a array contains 3 rows or 3 elements:a [0], a [1], a [2]. And each element is a one-dimensional array,It contains 4 elements of Figure 6.14 (ie 4 column elements). For example, the one-dimensional array represented by a [0] contains 4 elements:a [0] [0], a [0] [1], a [0] [2], a [0] [3]. It can be considered that the two-dimensional array is an "array of arrays", that is, the array a is composed of three one-dimensional arrays.

From a two-dimensional array perspective,a represents the address of the first element of the two-dimensional array,Now the first element is not an integer variable,But a one-dimensional array of 4 integer elements,So a represents the starting address of the first line (that is, the starting address of the 0th line,&A [0]), a + 1 represents the first address of line a [1],That is&a [1].

a [0], a [1], a [2] since they are one-dimensional array names,C++ also specifies that the array name represents the address of the first element of the array,So a [0] represents the address of the element in column 0 of the one-dimensional array a [0],That is&a [0] [0]. The value of a [1] is&a [1] [0], and the value of a [2] is&a [2] [0].

The address of the element in row 0 and column 1 can be directly written as&a [0] [1], or it can be expressed by pointer method.a [0] is the one-dimensional array name,The number 1 element in this one-dimensional array can obviously be represented by a [0] +1.

How to use the address method to get the value of a [0] [1]?Since a [0] +1 is the address of the a [0] [1] element,Then * (a [0] +1) is the value of the a [0] [1] element.And a [0] is unconditionally equivalent to * (a + 0),Therefore, you can also use * (* (a + 0) +1) to represent the value of a [0] [1] element.So on and so forth,* (a [i] + j) or * (* (a + i) + j) is the value of a [i] [j].

2) pointer variable to a multidimensional array element

① pointer variable to array element

[Example] Output the value of each element of the two-dimensional array.The method used here is to use pointer variables with a base type of integer to point to each element in turn.Output their values ​​one by one.

#include<iostream>
using namespace std;
int main ()
{
  int a [3] [4]={1,3,5,7,9,11,13,15,17,19,21,23};
  int * p;//p is a pointer variable whose base type is integer
  for (p=a [0];p<a [0] +12;p ++)
    cout<<* p<<""
  cout<endl;
  return 0;
}

The results are as follows:

1 3 5 7 9 11 13 15 17 19 21 23

A few notes about pointer variables to array elements:

p is a pointer variable to integer data,In the for statement, an initial value a [0] is assigned to p, which can also be written as "p =&a [0] [0]".

The condition for the end of the loop is "p

Execute "cout<* p;" to output the value of the column element currently pointed to by p,Then execute p ++ so that p points to the next column element.

② Pointer variable pointing to a one-dimensional array of m elements

You can define a pointer variable,It doesn't point to an integer element,Instead, it points to a one-dimensional array containing m elements.At this time, if the pointer variable p first points to a [0] (that is, p =&a [0]), then p + 1 does not point to a [0] [1], but points to a [1]. The length of the dimension array is in units,See Figure 6.17.

[Example] Output the values ​​of elements in any row and any column of the two-dimensional array.

#include<iostream>
using namespace std;
int main ()
{
  int a [3] [4]={1,3,5,7,9,11,13,15,17,19,21,23};
  int (* p) [4], i, j;
  cin>>i>>j;
  p=a;
  cout<<* (* (p + i) + j)<<endl;
  return 0;
}

The operation is as follows:

2 3↙
twenty three

Since "p=a" is executed, p is pointed to a [0]. So p + 2 is the starting address of the row number 2 in the two-dimensional array a (because p is a pointer variable pointing to a one-dimensional array,So p plus 1 points to the next one-dimensional array). * (p + 2) +3 is the address of the elements in the 2 rows and 3 columns of the a array.* (* (p + 2) +3) is the value of a [2] [3].

3) Use a pointer to an array as a function parameter

One-dimensional array names can be passed as function parameters,Multidimensional array names can also be passed as function parameters.

[Example] Output the value of each element of the two-dimensional array.The problem is the same as in Example 6.7, but this problem uses a function to achieve the output.Use a multidimensional array name as a function parameter.

#include<iostream>
using namespace std;
int main ()
{
  void output (int (* p) [4]);//function declaration
  int a [3] [4]={1,3,5,7,9,11,13,15,17,19,21,23};
  output (a);//Multi-dimensional array name as function parameter
  return 0;
}
void output (int (* p) [4]) //The formal parameter is a pointer variable to a one-dimensional array
{
  int i, j;
  for (i=0;i<3;i ++)
    for (j=0;j&4;j ++)
      cout<<* (* (p + i) + j)<<"";
  cout<endl;
}

The operation is as follows:

1 3 5 7 9 11 13 15 17 19 21 23
  • Previous Anatomy of the use of pointers as function parameters in C ++ programming
  • Next Parsing string manipulation functions and pointers in C ++