简体   繁体   English

C ++编译器读取“ int * p”时在做什么?

[英]What is the C++ compiler doing when it reads “int *p”?

What is the compiler doing when it reads "int *p?" 读取“ int * p”时,编译器在做什么? Does it assume p will become a pointer to an array of integers? 是否假设p将成为指向整数数组的指针? Can the star operator only be used with arrays? 星运算符只能与数组一起使用吗?

In C and C++, arrays and pointers are related to each other. 在C和C ++中,数组和指针相互关联。 In particular, this means that p can be made to point to a single int , or to the first element of an array of ints . 特别地,这意味着, p可以制成指向单个int ,或阵列的第一个元素ints

Does it assume p will become a pointer to an array of integers? 是否假设p将成为指向整数数组的指针?

No. It will allow p to hold the address of any integer. 。它将允许 p保留任何整数的地址。

It doesn't assume that it will. 它不假设会那样。 And if it does, it doesn't assume that it will be an array. 如果这样做的话,就不会假设它将是一个数组。

What is the compiler doing when it reads "int *p?" 读取“ int * p”时,编译器在做什么?

This will set up a variable called p which is a pointer to an integer. 这将设置一个名为p的变量,它是一个指向整数的指针。

Does it assume p will become a pointer to an array of integers? 是否假设p将成为指向整数数组的指针?

No. 没有。

p could just point to a single integer, though following (and even preceding) integer values could be accessed by using subsequent (or preceding) pointer values. p可以仅指向单个整数,尽管可以使用后续(或先前)指针值访问后续(甚至前置)整数值。 So it could also be pointing to the first element of an array of integers. 因此,它也可能指向整数数组的第一个元素。

*p or p[0] will return the integer at the end of the pointer * p或p [0]将在指针末尾返回整数

*(p + 1) or p[1] will return the integer immediately after the integer at the end of the pointer. *(p + 1)或p [1]将立即在指针末尾的整数之后返回整数。

*(p - 1) or p[-1] will return the integer immediately before the integer at the end of the pointer. *(p-1)或p [-1]将在指针末尾的整数之前立即返回整数。

(In fact there is a thing which is a "pointer to an array of integers", which has its own syntax (eg "int (*p)[10];") which has its own meaning, but that is a topic for another question.) (实际上,有一个东西是“指向整数数组的指针”,它具有自己的语法(例如“ int(* p)[10];”),它具有自己的含义,但这是一个主题。另一个问题。)

Can the star operator only be used with arrays? 星运算符只能与数组一起使用吗?

The star operator is used to refer to the value and the end of the pointer, either for reading or writing. 星号运算符用于引用值和指针的结尾,以进行读取或写入。

So whilst it is convenient for accessing sequences (arrays) of values, it can also be used to access a single value to get pass-by-reference semantics. 因此,虽然访问值的序列(数组)很方便,但它也可以用于访问单个值以获取按引用传递语义。

Here's an example that may help: 下面的示例可能会有所帮助:

#include <stdio.h>

main()
{
    int i = 10;
    int ia[2] = {1,2};

    int *p;
    p = &i;
    printf("%d\n", *p);
    p = ia;
    printf("%d\n", *p);
}

The output is 10 followed by 1. 输出为10,后跟1。

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

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