简体   繁体   English

C++中的指针混淆

[英]Pointers Confusion in C++

I am confused by the slides in my c++ course.我对我的 C++ 课程中的幻灯片感到困惑。 On the one hand in Example 1 int(*foo)[5] is a pointer to an integer array of 5 elements, but in Example 2 int(*numbers2)[4] points to an array of arrays (4 arrays) of type integer.一方面,在示例 1 中 int(*foo)[5] 是指向 5 个元素的整数数组的指针,但在示例 2 中 int(*numbers2)[4] 指向类型为的数组数组(4 个数组)整数。 How can these two have the same lefthand declaration but hold different types?这两个如何具有相同的左手声明但持有不同的类型?

#include <iostream>
using std::cout;
using std::endl;


int main() {

    //Example1
    int numbers[5] = { 1,2,3,4,5 };
    int(*foo)[5] = &numbers;
    int *foo1 = *foo;


    //Example2 
    int numRows = 3;
    int(*numbers2)[4] = new int[numRows][4];
    delete[] numbers2;


    return 0;

}

Check pointer declaration reference :检查指针声明参考

Because of the array-to-pointer implicit conversion, pointer to the first element of an array can be initialized with an expression of array type:由于数组到指针的隐式转换,指向数组第一个元素的指针可以用数组类型的表达式初始化:

 int a[2]; int* p1 = a; // pointer to the first element a[0] (an int) of the array a int b[6][3][8]; int (*p2)[3][8] = b; // pointer to the first element b[0] of the array b, // which is an array of 3 arrays of 8 ints

So essentially speaking what lefthand numbers2 and foo point to on the right hand side matters.所以从本质上讲,左边的numbers2foo指向右手边的东西很重要。

So in following numbers2 point to first element of temporary (yet unnamed) array which is an array of numRows arrays of 4 ints因此,在以下numbers2指向临时(尚未命名)数组的第一个元素,该数组是numRows数组的 4 个整数

 int(*numbers2)[4] = new int[numRows][4];

While foo points to first element of numbers which is an array of 5 intsfoo指向numbers第一个元素,它是一个包含 5 个整数的数组

int(*foo)[5] = &numbers;

The description in your question of example 2 is not exactly correct.您对示例 2 问题的描述不完全正确。

Try phrasing like this and you will see the parallelism.尝试这样的措辞,你会看到并行性。

  • foo is a pointer to the first object, each object is an integer array of 5 elements. foo是指向第一个对象的指针,每个对象都是一个包含 5 个元素的整数数组。 (As it turns out, the first one is the only one) (事实证明,第一个是唯一的)
  • numbers2 is a pointer to the first object, each object is an integer array of 4 elements. numbers2是指向第一个对象的指针,每个对象都是一个包含 4 个元素的整数数组。 (As it turns out, there are a total of numRows of them) (事实证明,它们总共有numRows

A pointer data type doesn't tell you the number of objects it points to, only the type of each one.指针数据类型不会告诉您它指向的对象数量,而只会告诉您每个对象的类型。

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

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