C++ Series Four: Arrays

1. Array definition and initialization

When defining an array, you need to specify the type and size of the array:

int myArray[10];

The above code defines an array of 10 integers. These integers are indexed starting at 0 and incremented by 1 unit.

C++ allows arrays to be initialized when they are defined. For example, the following code initializes the first three elements of the array to 1, 2, and 3.

int myArray[3] = {
    
    1, 2, 3};

If there are fewer values ​​in the initializer list than the size of the array, unspecified elements will be set to zero. For example, the following code will create a 10-element array where the first three elements are initialized to 1, 2 and 3 and the remaining elements are zero.

int myArray[10] = {
    
    1, 2, 3};

2. Multidimensional array

C++ allows the creation of multidimensional arrays, that is, arrays whose elements can be other arrays. Here is an example of a simple two-dimensional array:

int myArray[2][3] = {
    
    {
    
    1, 2, 3}, {
    
    4, 5, 6}};

The above code defines a two-dimensional array with 2 rows and 3 columns. We can access the elements of this array using two subscripts.

myArray[0][0] = 1;
myArray[0][1] = 2;
myArray[0][2] = 3;
myArray[1][0] = 4;
myArray[1][1] = 5;
myArray[1][2] = 6;

3. Character array

When defining a character array, you need to specify its size and type. Here is a simple example:

char myArray[10];

The preceding code defines a character array containing 10 characters.

You can also initialize character arrays when you define them. For example, the following code initializes a character array to the string "Hello, world!":

char myArray[] = "Hello, world!";

The last character in a C++ character array is usually the null character ('\0'), which indicates the end of the string. Therefore, there is no need to explicitly add a null character when initializing a character array, the compiler will add it automatically.

In C++, strings are actually character arrays. Therefore, strings can be handled in the same way as character arrays.

eg1

char myString[] = "Hello, world!";
cout << myString << endl;

output

“Hello, world!”

eg2

#include <string>
#include <iostream>

using namespace std;

int main() {
    
    
    string myString = "Hello, world!";
    char myArray[20];

    // 将字符串复制到字符数组中
    strcpy(myArray, myString.c_str());

    // 输出字符数组
    cout << myArray << endl;

    return 0;
}

The above code will create a string object myStringand a character array myArray. It will then use strcpy()the function to copy the string into a character array, and coutthe object to output the character array.

4. Summary

Naive record of learning C++ language 20 years ago

insert image description here

Guess you like

Origin blog.csdn.net/apr15/article/details/130536071