C基础知识(4):指针--p=&a和*p=a的区别详解

时间:2024-03-26 15:22:03

对于*p,[p = &a]和[*p = a]的区别详解

(1) p=&a就是用a的地址对p赋值,&p不改变,变的是p

(2) *p=a就是把p所指向的那一内存空间的值赋值为a,&p和p都不改变,变的是p所指向的那一内存空间的值

 1 #include <stdio.h>
 2 
 3 // 对于*p,[p = &a]和[*p = a]的区别详解
 4 int main() {
 5     int init = 0;
 6     // p=&a就是用a的地址对p赋值,&p不改变,变的是p
 7     int a = 10;
 8     int *p = &init;
 9     printf("[p] = %p; [*p] = %d; [&p] = %p;\n", p, *p, &p); //[p] = 0x7ffe12baad9c; [*p] = 0;  [&p] = 0x7ffe12baad90;
10     p = &a;
11     printf("[p] = %p; [*p] = %d; [&p] = %p;\n", p, *p, &p); //[p] = 0x7ffe12baad98; [*p] = 10; [&p] = 0x7ffe12baad90;
12     printf("[init] = %d;\n", &init, init); //0
13 
14     // *q=b就是把q所指向的那一内存空间的值赋值为b,&q q都不改变,变的是q所指向的那一内存空间的值,即init的值
15     int b = 20;
16     int *q = &init;
17     printf("[&b] = %p; [q] = %p; [*q] = %d; [&q] = %p;\n", &b, q, *q, &q); //[q] = 0x7ffe12baad9c; [*q] = 0;  [&q] = 0x7ffe12baad80;
18     *q = b;
19     printf("[&b] = %p; [q] = %p; [*q] = %d; [&q] = %p;\n", &b, q, *q, &q); //[q] = 0x7ffe12baad9c; [*q] = 20; [&q] = 0x7ffe12baad80;
20     printf("[&init] = %p; [init] = %d;\n", &init, init); //20
21     return 0;
22 }

代码分析:

C基础知识(4):指针--p=&a和*p=a的区别详解