简体   繁体   English

C / C ++指针解除引用

[英]C/C++ pointer dereferencing

If I have the following function... 如果我有以下功能......

void function(double *array)
{
    double a = array[3]; // Method 1
    double b = *(array + 3); // Method 2
}

Assume the array has 5 elements (I do know the length of the array ahead of time). 假设数组有5个元素(我确实知道数组的长度)。 The code compiles fine and runs ok. 代码编译良好,运行正常。 'a' and 'b' do contain the expected value. 'a'和'b'确实包含预期值。

In what instances would I use method 2 as opposed to method 1? 在什么情况下我会使用方法2而不是方法1?

E1[E2] is equivalent in C to (*((E1) + (E2))) by definition of [] operator. 根据[]运算符的定义, E1[E2]在C到(*((E1) + (E2)))是等价的。

Prefer the first notation as it is shorter and more readable. 首选符号,因为它更短,更易读。

both do the same. 两者都这样做。 that's like asking which method is better for accessing struct member allocated on heap : 这就像询问哪种方法更适合访问堆上分配的struct成员:

#include <stdio.h>
#include <stdlib.h>

struct s { int a;};
int main(void)
{
    struct s* x = malloc(sizeof(struct s));
    x->a = 2;  //method 1 OR
    printf("%d\n",x->a);
    (*x).a = 3;  //method 2
    printf("%d\n",(*x).a);
    free(x);
    return 0;
}

so use [] and -> operators. 所以使用[]->运算符。 it's good to know how they really work (dereferencing a pointer and adding offset to get to right address). 很高兴知道它们是如何工作的(取消引用指针并添加偏移量以获得正确的地址)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM