分配地址的指针 [英] assigning an address to a pointer

查看:127
本文介绍了分配地址的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一个分配给它的指针指向的值的地址的替代办法。例如,有以通常的方式:

  int类型的= 10;
INT * PTR;
PTR =安培; A;

但在某些地方我看到它声明如下:

 为int * PTR =安培; A;

是这两种等价的方式?我微微困惑,因为我始终认为* PTR是给人一种在的的,而不是地址。谁能解释一下?谢谢你。


解决方案

  

我微微困惑,因为我始终认为* PTR是给人一种价值,而不是地址。


这取决于它是否在初始化或赋值。

这是值得了解的1)声明,2)初始化之间的差异,以及3)分配。

 为int * PTR; // 1),这是不用初始化声明。为int * PTR =安培; A; // 2),这是申报**和**初始化(PTR初始化变量的地址)INT B = 10;
* PTR = B; // 3)这是分配,分配什么指向由​​ptr到变量b的值。


  • 在1) * 表示 PTR 是一个指针为int(但它没有指出任何有效的位置还)。

  • 在2) * 表示 PTR 为int的指针,它的初始值是地址变量 A

  • 在3) * 是尊重运营商,即让任何尖锐由ptr并为它分配变量的新值 B

I wanted to know if there are alternative ways of assigning a pointer the address of the value its pointing to. For example, there's the usual way:

int a = 10;
int *ptr;
ptr = &a;

but at some places I see it declared like:

int *ptr = &a;

Are both of these ways equivalent? I am slightly confused because I always considered *ptr as giving the value of a, and not the address. Could anyone please explain? Thanks.

解决方案

I am slightly confused because I always considered *ptr as giving the value of a, and not the address.

It depends on whether it's in an initialization or an assignment.

It's worth knowing the differences between 1) declaration, 2) initialization, and 3) assignment.

int *ptr; // 1) this is declaration without initialization.

int *ptr = &a; // 2) this is declaration **and** initialization (initialize ptr to the address of variable a)

int b = 10;
*ptr = b;   // 3) this is assignment, assign what pointed by ptr to value of variable b.

  • In 1) the * means that ptr is a pointer to int (but it has not pointed to any valid location yet).
  • In 2) the * means that ptr is a pointer to int, and its initial value is the address of variable a.
  • In 3) the * is the deference operator, ie getting whatever pointed by ptr and assign it a new value of variable b.

这篇关于分配地址的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆