c - 试图理解指针的引用和地址

标签 c

给出下面的代码为什么a和b的值会改变..p1和p2存储的是a和b的地址,为什么当p1和p2改变时a和b会改变

#include <stdio.h>


int main(int argc, char** argv) 
{

//&a stores address
//*p1 is a pointer

int a = 5, b = 10;
 int *p1, *p2;  //p1 and p2 are 2 pointers which can store int addressses

 p1 = &a;  //now p1 and p2 stores address of a and b
 p2 = &b; 



  printf("p1 storing address of a  = %d\n", *p1); 
 printf("p2 storing address of  b = %d\n", *p2);

 *p1=30;  
 *p2=40;

 printf("p1 assigning values to p1 pointer = %d\n", *p1); 
 printf("p2 assigning values to p2 pointer= %d\n", *p2);



 printf("a whose value is = %d\n", a); 
 printf("b = %d\n", b);

}

最佳答案

我认为如果您还打印指针本身而不仅仅是它们的内容,事情会更清楚。您可以为此使用 %p 说明符。

#include <stdio.h>

int main()
{
  int a = 10;
  int b = 20;
  int *p = &a;
  int *q = &b;

  printf("1) p is %p\n", p);
  printf("1) q is %p\n", q);
  printf("1) a is %d\n", a);
  printf("1) b is %d\n", b);

  p = q;

  /* At this point, I changed the value of p so that it  points to `b`
     just like `q` does. `a` and `b` are still unchanged. */ 
  printf("2) p is %p\n", p);
  printf("2) q is %p\n", q);
  printf("2) a is %d\n", a);
  printf("2) b is %d\n", b);

  *p = 30;

  /* Now that p points to `b`, dereferencing the pointer will affect `b`
     instead of `a` */
  printf("3) p is %p\n", p);
  printf("3) q is %p\n", q);
  printf("3) a is %d\n", a);
  printf("3) b is %d\n", b);
}

当你说 *p = something 时,你正在分配 p 指向的内存位置(可能是 ab 取决于您的设置方式)。另一方面,如果您执行 p = q,您会更改指针本身,而不是它指向的内容。

关于c - 试图理解指针的引用和地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36519740/

相关文章:

c - 为什么++ str和str + 1可以工作而str++不能工作?

c - 为什么我的程序不允许我进行第二次输入?

c - 按标签拆分 html

c - 我不断收到与类型相关的错误

c - 在 C 语言中使用 struct Aliasname* 作为函数返回类型

c++ - 在另一个文件中使用 lex 生成的源代码

c - 写入和读取某个文件

c - sem_init 分段故障错误

c++ - 是否可以在控制台中用 C 打印孟加拉语?

使用 gsl 的复杂矩阵乘法