C++017-C++ pointer and its application

C++017-C++ pointer and its application

insert image description here

Online practice:
http://noi.openjudge.cn/
https://www.luogu.com.cn/

C++ pointer and its application

reference:

CSP-J target

[ 4 ] Pointer
[ 4 ] Pointer-based array access
[ 4 ] Character pointer
[ 4 ] Pointer to structure

1. Pointer

A C/C++ pointer is a variable whose value is the address of another variable. Pointers can be used to store and retrieve the value pointed to by the address through the dereference operator (*). Through pointers, data in memory can be passed and manipulated between functions. Pointer is a very important concept in C/C++ language.

1. Definition and assignment of pointer variables

Before using the pointer, the pointer must be defined first. The general form of the type description of the pointer variable is:

 类型说明符 *变量名; 

Among them, * indicates that this is a pointer variable, the variable name is the name of the defined pointer variable, and the type specifier indicates the data type of the variable pointed to by the pointer variable. Let's first look at the difference between pointers and ordinary variables through an example.
1. Ordinary variable definition

 int a=3; 

The variable a is defined, which is of type int and has a value of 3. There is a memory space in the memory to store the value of a, and the access operation to a is to directly access this memory space. The location of the memory space is called an address, and the address for storing 3 can be obtained by operating on a with the address-taking operator "&": &a.

#include <iostream>

using namespace std;

int main()
{
    
    
    int a=3;
    cout<<a<<endl;
    cout<<&a<<endl;
    return 0;
}

insert image description here

2. Pointer variable definition

 int *p=NULL; 

A pointer variable p is defined, and p points to a memory space, which stores a memory address. Now the assignment is NULL (in fact, it is 0, which means a special empty address).

#include <iostream>

using namespace std;

int main()
{
    
    
    int a=NULL;
    cout<<a<<endl; // 0
    cout<<&a<<endl; // 0x61fe1c
    int *p=NULL;
    cout<<p<<endl; // 0
    cout<<&p<<endl; // 0x61fe10
    return 0;
}

insert image description here

3. Assign a value to the pointer variable p

 P=&a; 

That is, the memory space address (for example: XXX) of variable a is given to p. Obviously, the direct access to p is the address. Indirect operation through this address is the integer 3. The indirect operation of P
needs to use the pointer operator *, that is, the value of *p is 3. If there is a pointer variable p pointing to an integer variable, there are two ways to assign the address of the integer variable a to p:
① Method of initializing the pointer variable

 int a; 
 int *p=&a; 

② Method of assignment statement

 int a; int *p; p=&a; 

It is not allowed to assign a number to a pointer variable, so the following assignments are wrong:

 int *p;
 p=1000

. The assigned
pointer variable cannot be preceded by a "*" specifier, so the following assignments are also wrong:

*p=&a;

Full code:

#include <iostream>

using namespace std;

int main()
{
    
    
    int a; int *p; p=&a;
    // *p = &a; // invalid conversion from 'int*' to 'int' [-fpermissive]|
    // p=1000;  invalid conversion from 'int' to 'int*' [-fpermissive]|
    cout<<&a<<" -- "<<p<<endl; //
    return 0;
}

Several related operation instruction tables of pointers

illustrate sample
Pointer definition: type specifier * pointer variable name; int a=10; int *p;
Take address operator: &; p=&a;
Indirect operator: *pointer variable name; *p=20;
The pointer variable directly accesses the memory address; cout<<p; The result may be: 0x4097ce;
Indirect access is the value of the storage type; cout<<*p; The result is: 20

Pointer variables are the same as ordinary variables. Before using them, not only must they be defined, but they must also be assigned specific values. Unassigned pointer variables cannot be used. as defined

int a; int *p=&a;
// 则*p 表示 p 指向的整型变量

And p stores the starting address of the unit occupied by the variable a, so *p actually accesses the variable a, that is to say, *p is equivalent to a.

2. Pointer reference and operation

insert image description here

【Example 2】Input N integers and use pointer variables to access the output.

#include<cstdio>
using namespace std;
int a[101],n;
int main()
{
    
    
    scanf("%d",&n);
    for (int i=1; i<=n; i++)
        scanf("%d",&a[i]);
    int *p=&a[1]; //定义指针变量 int *p,初始化为数组开始元素的地址,即 a[1];
    printf("&a[1] %d \n",&a[1]);
    for (int i=1; i<=n; i++)
    {
    
    
        printf("%d --> %d \n",*p,p);
        p++; //p 指向下一个数,详见说明
    }
    return 0;
}

insert image description here
【illustrate】

"p++" means "add 1 in a generalized sense", not adding 1 to the value (address) of p, but increasing sizeof (int) according to the type int, that is, just "jumping" the space of one integer to reach the next integer.
Similar:
①, "p–" is to "skip" the space of one integer forward to reach the previous integer.
②, (p+3) is the address pointing to the third integer in the back.

[Example 3] An example of the use of untyped pointers.
Sometimes, a pointer points to different types of values ​​according to different situations. We can not define its type explicitly, just define an untyped pointer, and then use the method of forced type conversion to clarify its value as needed. type.

#include<iostream>
using namespace std;
int a=10;
double b=3.5;
void *p;
int main()
{
    
    
    p=&a; //p 的地址赋值
    cout<<*(int*)p<<endl; //必须明确 p 指向的空间的数据类型,详见说明
    p=&b;
    cout<<*(double*)p<<endl;
    p=&b;
    cout<<*(long long*)p<<endl;
    return 0;
}

insert image description here

It is necessary to clarify the data type of the space pointed to by p. If the type is different, not only the space size is different, but also the storage format is also different. If put

cout<<*(double*)p<<endl;

changed to

cout<<*(long long*)p<<endl;

The output will
be: 4615063718147915776.

2. Pointer-based array access

insert image description here

#include<cstdio> 
using namespace std; 
int main() 
{
    
     
 int a[5],i,*pa=a; //定义整型数组和指针,*pa=a 可以在下一行 pa=a; 
 for (i=0;i<5;i++) 
 scanf("%d",a+i); //可写成 pa+i 和 &a[i] 
 for (i=0;i<5;i++) 
 printf("a[%d]=%d\n",i, *(a+i)); //指针访问数组,可写成*(pa+i)或 pa[i]或 a[i] 
 return 0; 
}

insert image description here
insert image description here

[Example 6] Dynamic array, calculate prefix and array. b is the array definition of the prefix sum of array a:
b[i]=a[1]+a[2] +…+a[i], that is, b[i] is the sum of i elements of a.

#include<cstdio>
using namespace std;
int n;
int *a; //定义指针变量 a,后面直接当数组名使用
int main()
{
    
    
    scanf("%d",&n);
    a=new int[n+1]; //向操作系统申请了连续的 n+1 个 int 型的空间
    for (int i=1; i<=n; i++)
        scanf("%d",&a[i]);
    for (int i=2; i<=n; i++)
        a[i]+=a[i-1];
    for (int i=1; i<=n; i++)
        printf("%d ",a[i]);
    return 0;
}

insert image description here

[Description]
Advantages of dynamic arrays: In OI, it is more tangled in the case of large data that may exceed the space. Small arrays are used to divide only parts, and large arrays may burst into space (0 points). Using "Dynamic Array" can meet the needs of big data as much as possible on the premise of ensuring that small data is no problem.

3. Pointers and strings

insert image description here

#include<cstdio>
using namespace std;
int n;
int *a; //定义指针变量 a,后面直接当数组名使用
int main()
{
    
    
    char str1[]="I love China!";
    printf("%s\n", str1);
    char *str="I love China!";
    printf("%s\n", str);
    return 0;
}

2. String pointer as a function parameter
To transfer a string from one function to another, you can use the method of address transfer, that is, use the character array name as a parameter or use a pointer variable pointing to a character as a parameter. The string content can be changed in the called function, and the changed string can be obtained in the calling function.

[Example 8] Input a character string with a maximum length of 100, store it in a character array, store the character string in reverse order, and output the character string stored in reverse order. (Here, the character pointer is used as the function parameter)

#include<cstdio>
#include<cstring>
using namespace std;
void swapp(char &a,char &b) //交换两个字符的位置
{
    
    
    char t;
    t=a;
    a=b;
    b=t;
}
void work(char* str)
{
    
    
    int len=strlen(str); //strlen(str)这个函数返回的是 str 的长度,
//需包含头文件 cstring
//这个函数的原型是"size_t strlen(const char* str)"
    for (int i=0; i<=len/2; ++i)
        swapp(str[i],str[len-i-1]);
}
int main()
{
    
    
    char s[110];
    char *str = s;
    gets(s);
    work(str);
    printf("%s",s);
    return 0;
}

insert image description here

4. Structs and pointers

insert image description here

#include<cstdio>
using namespace std;
struct student
{
    
    
    char name[20];
    char sex;
    int score;
} s[3]= {
    
    {
    
    "xiaoming",'f',356},
    {
    
    "xiaoliang",'f',350},
    {
    
    "xiaohong",'m',0}
};
int main()
{
    
    
    student *p;
    printf("Name Sex Score\n");
    for (p=s; p<s+3; p++)
        printf("%-9s%3c%7d\n",p->name,p->sex,p->score);
    return 0;
}

insert image description here

insert image description here

In practice:

http://noi.openjudge.cn/

Summarize

This series is a C++ learning series, which will introduce C++ basic grammar, basic algorithms and data structures. This article is a C++ pointer and its application case, including relevant case exercises.

Guess you like

Origin blog.csdn.net/m0_38139250/article/details/130174479