The use of strings and arrays and pointers in C + + to explain _c language

Source: Internet
Author: User
Tags constant first row

C + + strings and pointers
In C + +, you can access a string in 3 ways (the first two methods are described in chapter 5th).
Storing a string with a character array

The example defines a character array and initializes it, and then prints the string.

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


Run-time output:

I Love china!


storing strings with string variables

The example defines a string variable and initializes it, and then prints the string.

#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

The example defines a character pointer variable and initializes it, and then prints 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 can be either subscript or a pointer method.

"Example" copies the string str1 as a string str2.

Defines the two-character array str1 and STR2, and then sets two pointer variables P1 and P2, pointing to the characters in the two-character array, by changing the value of the pointer variable to point to different characters in the string to enable the character to be copied.

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

The results of the operation are:

STR1 is:i Love china!
STR2 is:i Love china!


This example is used to illustrate how to use character pointers. In fact, for example 6.13来, it is very simple to deal with string variables:

  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, and each array element occupies a storage cell in memory, all of which have a corresponding address. The pointer variable can point to a variable, of course, and you can point to an array element (place the address of an element in a pointer variable). A pointer to an array element is the address of an array element.

  int a[10];  Defines an integer array A, which has 10 element
  int *p;//defines a pointer variable p p=&a[0]; with a base type integer
  and assigns the address of the 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 ordinal 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 address of P's initial value is a[0]


can also be written

  int *p=a; Same effect as previous line


You can reference an array element by pointer. Suppose P has been defined as a pointer variable with an integer base type and has assigned the address of an integral array element to it so that it points to an array element. If you have the following assignment statement:

  *p=1; Assigns a value of 1 to the array element to which P is currently pointing


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

If P's initial value is &a[0], then:
1 P+i and A+i are the addresses of a[i], or they point to the first element of array A, see figure 6.12.

2) * (P+i) or * (A+i) is the array element that p+i or a+i points to, that is, a[i].

As you can see, [] is actually a variable address operator. The solution to A[i] is to calculate the address of an array element by pressing A+IXD, and then find the value in the cell that this address points to.

3 A pointer variable that points to an array element can also be subscript, such as p[i] and * (p+i) equivalent.

Based on the above description, you can refer to an array element by using the following methods:
Subscript method, such as a[i] form;
Pointer method, such as * (A+i) or * (P+i). Where a is the array name and p is the pointer variable that points to the element of the array. If the value of P is already a, then * (P+i) is a[i]. You can find the element you want by pointing to the pointer to an array element. Using the pointer method can make the target program of high quality.

"Example" outputs all the elements in an array. Suppose there is an integer array a with 10 elements. There are 3 ways to output values for 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];//referencing array element a[i]
  cout<<endl;
  for (i=0;i<10;i++)
   cout<<a[i]<< ""; Referencing an array element a[i]
  cout<<endl;
  return 0;
}

The operating conditions are as follows:

9 8 7 6 5 4 3 2 1 0↙ (enter 10 element value) 9 8 7 6 5 4 3 2 1       (output 0 element values)

2) pointer method.
Replace the "a[i]" in lines 7th and 10th of the above procedure with the words "* (a+i)" and the operation is the same as (1).

3 point to the array element with the pointer variable.

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

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

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

Using subscript method is more intuitive, can directly know is the first few elements. Using address method or pointer variable method is not very intuitive, it is difficult to quickly determine which element is currently being processed. When you point to an array element with a pointer variable, be aware that the pointer variable p can point to a valid array element, and you can actually point to the memory cells later in the array. If there is

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


When you use pointer variables to point to an array element, you should be sure to point to the elements that are valid in the array.

Pointers to array elements are more flexible and must be carefully calculated. Let me give you a few examples.

If you first point p to the first element of array a (that is, p=a), then:
1) p++ (or p+=1). Causes P to point to the next element, that is, a[1]. If you use *p, you get the value of the next element a[1].

2) *p++. Because of + + and * with priority, the combination direction is from right and left, so it is equivalent to * (p++). The effect is to get the value of the variable that p points to (that is, *p), and then add the value of P to 1. The last for statement in the example 6.5 (3) Program:

  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) different effects. The former is the first to take the *p value, then p plus 1. The latter is to make P plus 1 first, then take *p. If the initial value of P is a (i.e. &a[0]), the output * (p++) gets the a[0], and the output * (++p) Gets the value of a[1.

4) + + (*p) + + indicates the element value that P points to plus 1, i.e. (a[0]) + +, if a[0]=3, then (a[0]) + + has a value of 4. Note: The element value plus 1, not the pointer value plus 1.

5 if P is currently pointing to A[i], then
* (p--) First to P "*" operation, get A[i], and then the P minus 1,p point to a[i-1].
* (++p) First make p from 1, then the * operation, get a[i+1].
* (--p) first make p since minus 1, then the * operation, get a[i-1].
Using the + + and--operators with pointer variables that point to array elements is very effective, so that pointer variables can be moved automatically forward or backward, pointing to the next or previous array element. For example, to output 100 elements of 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++;
  }


In the *p++ form of the operation, it is easy to make a mistake, must be very careful to figure out whether to take the P value first or the P plus 1.
Receive array address with pointer variable as function parameter

The arguments that can be used with the array masterpiece function are described earlier. It has been emphasized many times before: array names represent the addresses of the first elements of an array. The address of the first element of an array is passed with the arguments of the function of the array masterpiece. It is easy to assume that using a pointer variable as a function parameter can also receive the address of the first element of an array passed from the argument (at which point the argument is an array name). The following is a function parameter with a pointer variable.

"Example" arranges 10 integers in order from small to large. On the basis of the example 5.7 program, the parameter is changed 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++)//input 10 number
    cin>>a[i];
  cout<<endl;
  Select_sort (a,10); function call, array masterpiece argument
  cout<< "the sorted array:" <<endl;
  for (i=0;i<10;i++)//Output 10 ordered number of
    cout<<a[i]<< "";
  cout<<endl;
  return 0;
}
void Select_sort (int *p,int N)///with pointer variable as parameter
{
  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;//use pointer to access array element t=* (p+k), * (p+k) =* (p+i)
    ; * (p+i) =t;
  }

Operating conditions

The C + + compilation system handles the parameter group name as a pointer variable.

In fact, a function call does not exist a parameter group that occupies the storage space, only the pointer variable.

The combination of real participation in formal parameters has the following 4 forms:
Argument formal parameters
Array array group name

Array name pointer variable

Pointer variable array name
Pointer variable pointer variable

On this basis, we also need to explain a problem: the real parameter group name A is a fixed address, or a pointer-type constant, so it is impossible to change the value of a. Such as:

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

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

F (array[], int n)
{
  cout<<array;//output ARRAY[0] value
  array=array+3;//pointer variable array value changed, pointing to Array[3]
  cout<<*arr<<endl; Value of output ARRAY[3]
}

multidimensional arrays and pointers

You can point to an element in a one-dimensional array with a pointer variable, or you can point to an element in a multidimensional array.

1 The address of the multidimensional array element
Has 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. A array contains 3 lines, or 3 elements: a[0],a[1],a[2]. And each element is a one-dimensional array that contains 4 figure 6.14 elements (i.e. 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]. You can think of a two-dimensional array as an array of arrays, that is, the array A is made up of 3 one-dimensional arrays.

From the point of view of a two-dimensional array, a represents the address of the first element of a 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 row (that is, the starting address of line No. 0, &a[0]), and the a+1 represents the first address of the a[1] line, i.e. &A[1].

A[0],A[1],A[2] Since it is a one-dimensional array name, and C + + stipulates that the array name represents the first element address of the array, A[0] represents the address of the 0-column element in the one-dimensional array a[0], that is, &a[0][0. The value of a[1] is the value of &a[1][0],a[2] is &a[2][0].


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

To get the value of a[0][1], how do you mean by address law? 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), so you can also use * (* (a+0) +1) to represent the value of the a[0][1 element. And so on, * (A[I]+J) or * (* (a+i) +j) is the value of a[i][j].

2 pointer variable pointing to multidimensional array elements

① pointer variable pointing to an array element
"Example" outputs the values of the elements of a two-dimensional array. The method used here is to point to each element with a pointer variable of the base type as an integer, outputting their value individually.

#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 the pointer variable for the base type integer for
  (p=a[0];p <a[0]+12;p++)
    cout<<*p<< "";
  cout<<endl;
  return 0;
}

The results of the operation are as follows:

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

A few notes on pointer variables that point to an array element:
P is a pointer variable that points to an integer data, and it can be written as "p=&a[0][0]" in the For statement, a[0 the initial value of P.
The condition for the end of the loop is "p<a[0]+12", which, as long as the p<a[0]+12 is satisfied, continues to execute the loop body.
Execute "cout<<*p;" Outputs the value of the column element that P is currently referring to, and then executes 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 that does not point to an integer element, but to a one-dimensional array that contains m elements. At this point, if the pointer variable p first points to a[0] (that is, p=&a[0]), then the p+1 does not point to a[0][1, but instead points to the increment of the a[1],p in the length of the one-dimensional array, as shown in Figure 6.17.

The example outputs the value of any column element in a 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 operating conditions are as follows:

2 3↙
23

Because of the execution of "P=a", the P points to a[0]. So p+2 is the starting address for a row with ordinal 2 in two-dimensional array A (because p is a pointer variable to a one-dimensional array, so P plus 1 points to the next one-dimensional array). * (p+2) +3 is an array of 2 rows of 3 column element addresses. * (* (p+2) +3) is the value of a[2][3].

3) using pointers to the array as function parameters
A one-dimensional array name can be passed as a function parameter, and multidimensional array names can also be passed as function parameters.

"Example" outputs the values of the elements of a two-dimensional array. The topic is the same as the example 6.7, but the subject uses a function to achieve output, using the multidimensional array masterpiece function parameters.

#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); Multidimensional array masterpiece function parameter return
  0;
}
void output (int (*p) [4])//parameter is a pointer variable
{
  int i,j that points to a one-dimensional array;
  for (i=0;i<3;i++) for
    (j=0;j<4;j++)
      cout<<* (* (p+i) +j) << "";
  cout<<endl;
}

The operating conditions are as follows:

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.