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

查看:26
本文介绍了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.

我应该什么时候使用 &*?

When should I use & and *?

推荐答案

你有指针和值:

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

您可以使用 & 将值转换为指针:

You turn a value into a pointer with &:

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天全站免登陆