Detailed explanation of the connection between C++ arrays, strings, and pointers

Array

1. Definition
Store multiple values ​​of the same type.

int a[5];-is an int array, not an array
5-integer constant, const value (variable), constant expression

const int n = 5;
char a[n] = {
    
     "asd" };
cout << a;

2. Initialization

It can be initialized when the array is defined.
Two ways:

  1. List {}, you can use {} for strings
  2. Subscript assignment
//列表
int a[10] = {
    
    1,2,3};
//字符
char a[] = "asd asd";
//下标赋值
int a[5] = 4;

Special case

int a[10] = {
    
    1,2,3};//剩余默认初始化为0
int b[5] = {
    
    0};//全零的数组

3. Note that the
compiler will not check whether the subscript is valid, and will not report an error if there is a problem

4. Array classification

Character array-char array

//以字符的形式初始化——数组
char str[10] = {
    
     '1','2' };//12
//以字符串的形式初始化——不仅是数组,更是字符串
char str_array[10] = {
    
    "jiang"};//jiang,可以不加{}

Non-character array-int, double array, etc.

1 int a[10]={
    
    1,2,3};
2 cout << a <<endl ; //按16进制输出a的值(地址

String

1. Define
characters in consecutive bytes of memory.
(Consecutive bytes are fine, you don’t need to be contiguous in bytes)

a. Characters-[(letters, numbers, punctuation and blank characters)]
b. A space in the string is counted as one character.
Blank characters: space, (TAB) and carriage return (Enter).

2. The way C++ handles strings is
char array (other non-character arrays are not acceptable)
string class

Array and string

1. Connect
the characters of consecutive bytes in the memory, which means that they can be stored in the form of a char array .
[Non-character array (int type) cannot be stored because it is not a string]

Non-character array-without quotes It
is an array, but not a string

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

Character array-single quote or double quote

char str[10] = {
    
     '1','2' };//12——char数组但不是字符串
char str_2[10] = {
    
     '1','2','\0' };//12——字符串

char str_3[10] = {
    
    "sdf"};//字符串常量
char a[] = "asd asd";//字符串常量另一种表达形式

2. Two forms of char array processing string

//没有'\0',就仅仅是char数组
char a[10] = {
    
    'a','b','\0'};//字符串
//主流表示法,自动补充\0
char b[10] = {
    
    "ab"};//字符串常量(和上面不一样)
char c[10] = "ab";//字符串常量

Strings and pointers

Each string occupies a continuous storage space in the memory , and has a uniquely determined first address.
(Characters of consecutive bytes in the memory, and have a unique first address)

1. Character pointer
Assign the first address of the character string to the character pointer, which can make the character pointer point to a character string .

char *ptr = "Hello";

Arrays and pointers

The variable name of the array is the first address of the array

p = &p[0]

p[0] = *p

Guess you like

Origin blog.csdn.net/qq_43641765/article/details/111455424