当前位置:网站首页>Pointer (preliminary solution of C language)

Pointer (preliminary solution of C language)

2022-08-10 13:33:00 quack quack

In computer science, a pointer is an object in a programming language. Using an address, its value directly points to a value stored in another place in the computer's memory. The desired variable unit can be found through the address. It can be said that the address points to theThe variable unit is therefore called an "address" of the image.It means that the memory cell with its address can be found.

#include
int main() {

printf("%d\n",sizeof(char*));
printf("%d\n", sizeof(int*));
printf("%d\n", sizeof(double*));
printf("%d\n", sizeof(short*));
return 0;
}

*Prove that the pointer occupies four bytes

*value character & address character

  • The type of the pointer determines the size of the space that can be accessed when the pointer is dereferenced, and determines what type the pointer variable points to

int 4 bytes

char 1 byte

double 8 bytes

#define _CRT_SECURE_NO_WARNINGS
#include

int main() {
    int a[10] = {0};
    int* p=a ;//数组名-首元素的地址
    
    int i=0;
for (i = 0; i < 10; i++) {
*(p + i)=1;
  }
printf("%d",a[9]);


Return 0;
}

  • Wild pointer (where the pointer points to is unknown)

Cause: 1, pointer not initialized

2, pointer out-of-bounds access

int a[]={0};

int *p=a;

int i=0;

for(i=0;i<11,1++){

p++;

}

3, the address in the calling function is returned to the system

#define _CRT_SECURE_NO_WARNINGS
#include
int *test() {
int a = 10;
return &a;
}
int main() {
int* p = test();//After the function is called, the allocated address of 10 will be automatically cancelled, and *p will become a wild pointer
*p = 20;
Return 0;
}

*p=NULL pointer cannot be accessed when it is empty

  • Pointer Arithmetic

1, pointer + integer

2, pointer-integer

3, the relational operation of pointers

Pointer+-Integer:

#define _CRT_SECURE_NO_WARNINGS
#include
int main() {
int a[10] = { 1,2,3,4,6,7,8,9,10 };
int* p = a;
int s= sizeof(a)/sizeof(a[0]),i=0;
for (i = 0; i < s; i++) {
printf("%d\n", *p);
p=p+1;
return 0;
}

#define _CRT_SECURE_NO_WARNINGS
#include
#define arr 2
int main() {
int v[arr];
int* p;
int i = 0;
for (p = &v[0]; p <&v[arr];) {
*p++ = 0;
}
for (i = 0; i < 2; i++) {
printf("%d", v[i]);
} }

return 0;
}

The big address-small address is the number of intermediate elements + 1, and the result is unpredictable when two different array addresses are subtracted

#define _CRT_SECURE_NO_WARNINGS
#include
#define arr 2
int main() {
int a[10] = {1,2,3,4,5,6,7,8,9,10};
int* p,b;
b=&a[9] - &a[0];
printf("%d", b);
return 0;
}

原网站

版权声明
本文为[quack quack]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/222/202208101300589664.html