C + + Auto is a confusing situation when initializing with multidimensional arrays

Source: Internet
Author: User

First look at the following procedure:

intarr[1][Ten] = {0,1,2,3,4,5,6,7,8,9}; for(Auto *p = arr;p! = End (arr); p++) {cout<<"P is"<< typeid (P). Name () <<Endl; cout<<"*p is"<< typeid (*p). Name () <<Endl;} for(Auto *Q:arr) {cout<<"Q is"<< typeid (q). Name () <<Endl; cout<<"*q is"<< typeid (*q). Name () <<Endl;} for(Auto &R:arr) {cout<<"R is"<< typeID (R). Name () <<Endl;}

The result of the program running is

P is int (*) [10]

*p is int [10]

Q is int *

*Q is int

R is int [10]

In C + +, operations on arrays are usually performed on pointers. When you initialize a pointer with an array name, you get a pointer to the first element of the array.

The essence of a multidimensional array is an array of elements. such as int a[3][4] is an array of three elements whose elements are arrays of four integral elements. Therefore, auto *p = A,p is a pointer to the first element of array A, which is a pointer to an array with four integral elements, and *p is the first element of a, which is an array of four integral elements.

In range for, however, auto *q = arr is a pointer to the first element of an array element (an array with four elements) . So q is a pointer to an integral type element. If the array has more dimensions, such as the first element of int a2[3][4][5],a2 is an array with four elements, all four elements are arrays of five integral elements. In this case, the type of p in the for (auto *P:A2) is int (*) [5].

To prevent errors caused by this difference, you can use a reference in range for. For Auto &r:arr, R is a reference to an array element with the same type as auto *p = arr, *p.

C + + auto is a confusing situation when initializing with multidimensional arrays

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.