在C指针:时要使用的符号和星号? [英] Pointers in C: when to use the ampersand and the asterisk?

查看:127
本文介绍了在C指针:时要使用的符号和星号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始接触球,我稍微困惑。我知道&安培; 表示一个变量的地址和 * 可在指针变量的前面被用来获得由该指针指向的对象的值。但事情有不同的工作,当你使用数组,字符串或工作时,你调用函数与变量的指针副本。这是很难看到里面所有这一切逻辑的模式。

I'm just starting out with pointers, and I'm slightly confused. I know & means the address of a variable and that * can be used in front of a pointer variable to get the value of the object that is pointed to by the pointer. But things work differently when you're working with arrays, strings or when you're calling functions with a pointer copy of a variable. It's difficult to see a pattern of logic inside all of this.

当我应该使用&放大器; *

推荐答案

您有三分球和值:

int* p; // variable p is pointer to integer type
int i; // integer value

您把一个指针变成价值与 *

You turn a pointer into a value with *:

int i2 = *p; // integer i2 is assigned with integer value that pointer p is pointing to

您把一个值的指针与&安培;

int* p2 = &i; // pointer p2 will point to the address of integer i

编辑:
在数组的情况下,它们被视为非常像指针。如果你认为他们是指针,你将使用 * 来得到在他们里面的值如上所述,但也有采用另一种更常见的方式 [] 运营商:

In the case of arrays, they are treated very much like pointers. If you think of them as pointers, you'll be using * to get at the values inside of them as explained above, but there is also another, more common way using the [] operator:

int a[2];  // array of integers
int i = *a; // the value of the first element of a
int i2 = a[0]; // another way to get the first element

要获得第二个元素:

int a[2]; // array
int i = *(a + 1); // the value of the second element
int i2 = a[1]; // the value of the second element

所以 [] 索引操作符是 * 运算符的一种特殊形式,它的工作原理是这样的:

So the [] indexing operator is a special form of the * operator, and it works like this:

a[i] == *(a + i);  // these two statements are the same thing

这篇关于在C指针:时要使用的符号和星号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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