C++ pointer knowledge points excerpt

Pointer is an important concept in C language, and it is also an important feature of C language. In the C language, pointers are widely used, and they are closely related to the transfer of data between arrays, strings, and functions. It can be said that without mastering pointers, there is no mastering the essence of C language.
Pointers can quickly and directly process various types of data in memory, and can also provide a concise and convenient method for data transfer between functions. Correct and proficient use of pointers is conducive to writing efficient programs, but improper use of pointers can easily lead to serious errors. The pointer is very flexible and dangerous.

Define pointer variables

Pointer variables (referred to as pointers) are variables that store addresses. Compared with the general variable declaration, its declaration form only has an asterisk * in front of the variable name. Let's look at two examples.
example 1:

int *p;

In this example, the variable p is declared as a pointer to an integer value (that is, the address of an integer variable can be stored in the variable p). Here * in the declaration statement is a pointer specifier, indicating that the declared variable is a pointer variable.
Example 2:

float *xPtr, *yPtr, f;

This example declares two pointers xPtr and yPtr that point to floating-point values ​​and a floating-point variable f.

The nature of the pointer

① The pointer can be assigned NULL or an address. A pointer with the value NULL does not point to any address;
② A pointer is an address with specific attributes. The address alone only knows that the data is stored in a certain location in the memory, but how to access the data at that location (that is, how many bits are accessed and how to access it) also needs to be clarified by the pointer type;
for example: use an int type pointer to access the point it points to In the case of data, it will read 32 bits at a time (int type data is 32 bits), and use the integer data format to access the data. So a pointer is not just an address, it must also have specific attributes (types).
③ The array name can be regarded as a special address. First, the array name is the address (the first address of the array), and the number group name has attributes (the type of the array element), so the array name can be assigned to the pointer variable of the same type.
E.g:

char s[10] = "China";//字符类型的数组表示字符串
char *sptr = s;

After the second statement is assigned, sptr has the same value as s, that is, the first address of the array, which is the address of the unit storing the character'C'.
④ To access the unit pointed to by the pointer, you can use the indirect reference operator * (different from the * in the previous declaration statement, where * is an operator in the expression). * is also called the double reference operator, which returns The object pointed to by its operand (pointer);
for example:

char s[10] = "China";
char *sptr = s;
cout << *sptr;

The character stored in the unit pointed to by the pointer sptr will be output (because sptr is a pointer of type char), that is, the character'C' will be output. (The first element of the array)
⑤ The unit pointed to by the pointer can be modified through the multiple reference of the pointer;
for example:

char s[10] = "China";
char *sptr = s;
*sptr = 'c';

The above code will modify the uppercase character'C' in the storage unit to the lowercase character'c'.
Please note the difference between the output statement of the previous code and the following code statement:

char s[10] = "China";
char *sptr = s;
cout << sptr;

This statement will output the string "China". When learning character arrays before, you should know that the statement cout << s; will output the entire string stored in the array s. In fact, when C++ uses cout to output a char pointer, it does not output the value (address) of the character pointer, but output The string starting from this address (output one character one by one until it hits'\0'). So cout << sptr; has the same effect as cout << s;, which is to output the string "China".
⑥ To access a character string is generally to use the address of the first character of the character string;
⑦ The pointer can also participate in arithmetic operations. The pointer adds or subtracts an integer n, and the result of the operation is to point to the nth variable behind or in front of the variable pointed to by the pointer.
For example: before sptr points to the storage unit of the character'C', execute the statement sptr++; afterwards sptr points to the storage unit of the character'h'. The following statement:

while(*sptr != ‘\0)
    sptr++;
//则可以使指针 sptr 指向该字符串后面的 '\0'。如果要输出字符串中的部分内容,也可以通过修改指针实现,如:
char s[10] = “China”;
char *sptr = s;
sptr++;
cout << sptr;
//上述代码执行语句`sptr++;`后,指针 sptr 指向了字符 'h' 的存储单元,此时`cout << sptr;`输出的是 sptr 指向的字符串,即“hina”。
//同类型的两个指针可以参与各种关系运算,其结果可以反映两指针所指向的地址之间的位置前后关系。
//例如:
int a[10];
int *p = a, *q = &a[1];
if(p > q)
    cout << “p>q” << endl;
else
    cout << “p<=q” << endl;

The value of a is stored in the pointer p in the above code, which is the address of a[0], the address of a[1] is stored in q, and the array elements are stored sequentially and consecutively, so the value of q is better than The value of p is large, and the program outputs p<=q.

Pass parameters with pointers

There are two ways to pass parameters for C and C++ function calls: pass by value and pass by reference.
Passing by value is only the passing of values, and the called function cannot modify the value
of the actual parameter ; passing by reference is the storage unit where the actual parameter and the formal parameter share the actual parameter, so the called function can modify the value of the actual parameter by modifying the formal parameter.
If you pass the pointer value by value, you can achieve an effect similar to passing by reference.
E.g:

#include <iostream>
using namespace std;
// 函数inc:将p指向的整数值加
// 参数:p-int类型指针,指向要加的整数
void inc(int * p)
{
    
    
    (*p)++;     // *p 访问 p 指向的单元,++ 将该单元的数据加
    // 注意不能是 *p++, 因为 * 和 ++ 优先级相同,且右结合,这种写法修改的是 p 的值,而不是 *p 的值
}
int main()
{
    
    
    int a = 10;
    inc(&a);     // 调用 inc 函数,修改 a 的值(传递的是 a 的地址)
    cout << a << endl;     // 输出 a 的值
    return 0;
}

The output of the above program is 11, where the called function inc only modifies the value of the local variable a in the main function, but does not modify the value of the actual parameter (the actual parameter is &a, that is, the address of a remains unchanged).

你理解了吗?猜猜下面的程序会输出什么,做对了说明你理解得差不多了:
#include<iostream>
using namespace std;
int main(){
    
    
	int a=0;
	int *b=&a;
	cout<<&a<<' '<<*b<<' '<<b<<' '<<a<<' '<<&*b<<' '<<*&a<<' '<<&*b<<' '<<*&*b<<' '<<&*&a<<endl;
	return 0;
}
(答案请看文末~

String manipulation functions

C and C++ provide a series of functions for manipulating strings. To use these functions, just include string.h in the header file of the code.
The commonly used string processing functions are shown in the following table:
Insert picture description hereInsert picture description hereInsert picture description here

strstr function

To find a substring in a long string, you can use the strstr function. The function prototype of this function is:

char* strstr(const char* s1, const char* s2);

This function starts from the first character in the string pointed to by s1 and searches backwards in order to find the same substring as the string pointed by s2. If the search succeeds, it returns the first address of the first occurrence of the substring, otherwise it returns NULL.
E.g:

char *a="abcdeabcde";
char *b="bcd";
cout<<strstr(a,b)<<endl;

The output result of this program is "bcdeabcde", because the return value of strstr(a, b) is the first address of the first occurrence of "bcd" in "abcdeabcde", so when outputting with cout, start with the characters at this position one by one Output until'\0', which is the string "bcdeabcde".
Of course, when searching for a substring, you can also start from a certain position in the long string.
E.g:

char *a="abcdeabcde";
char *b="bcd";
cout<<strstr(a+4,b)<<endl;

The output of this program is "bcde". Because a+4 gets a new address, that is, the address of the first character'e' in the string pointed to by a, start from this position to find the string'bcd' pointed to by b, and get the first character starting from the character'e' The address where "bcd" appears, and then use cout to output the character string starting at that address, that is, "bcde".

strlen function

In addition, where to start searching for substrings next time? It should be the starting position of the last time the substring was found plus the length of the substring. Among them, the function strlen can calculate the length of a string, and its function prototype is:

int strlen(const char *s);

The function strlen has only one parameter s, which is a character pointer representing a string. The function calculates the length of the string pointed to by s and returns it.
E.g:

char *a="x";
char *b="Hello world!";
cout<<strlen(a)<<endl;  // 输出 1
cout<<strlen(b)<<endl;  // 输出 12

sizeof() function

The number of bytes occupied by the output:

#include<iostream>
#include<cstring>
using namespace std;
int main(){
    
    
	char a[10];
	cout<<sizeof(a)<<' ';
	cout<<sizeof(int)<<' ';
	cout<<sizeof(int*)<<' ';
	cout<<sizeof(char)<<' ';
	cout<<sizeof(char*)<<' ';
	cout<<sizeof(double)<<' ';
	cout<<sizeof(double*)<<' ';
	cout<<sizeof(float)<<' ';
	cout<<sizeof(float*)<<' ';
	return 0;
}

Output:

10 4 8 1 8 8 8 4 8
  • You can also use sizeof() to calculate 同类型元素the number of elements in an array:
#include<iostream>
#include<cstring>
using namespace std;
int main(){
    
    
	char a[]={
    
    1,2,3,4,5,6,7,45,6232};
	cout<<sizeof(a)/sizeof(a[0]);
	return 0;
}
输出:9

上面测试答案如下:
0x6ffdf4 0 0x6ffdf4 0 0x6ffdf4 0 0x6ffdf4 0 0x6ffdf4

Guess you like

Origin blog.csdn.net/interestingddd/article/details/114311893