A brief discussion on C + + array passing methods cannot be computed to the correct array size with sizeof

Source: Internet
Author: User

In C + + we often use sizeof () to calculate the size of an array

For example:

1#include <iostream>2 using namespacestd;3 4 voidLength (int*p)5 {6cout<<sizeof(p) <<"  "<<sizeof(int) <<Endl;7 }8 9 intMain ()Ten { One     intN; A     intPirce[] = {0,1,5,8,9,Ten, -, -, -, -, -}; -  -      for(intI=0; i<sizeof(Pirce)/sizeof(int); i++) the     { -cout<<pirce[i]<<" "; -     } -cout<<Endl; +  - Length (pirce); +  A     return 0; at}

The result of running this code is as follows:

0 1 5 8 9 10 17 17 20 24 30

8 4

It can be seen in the main method that sizeof (Pirce)/sizeof (int) is correct and it prints out the elements in the array so

Passing an array in the length () method finds the result of sizeof (p)/sizeof (int) to be 2

Why???

This is because the array is passed into the method with the first address of the array, so it becomes a pointer, so it is not possible to use sizeof to calculate the size of the group.

Ps: The array here is a static array, not a new array;

A brief discussion on C + + array passing methods cannot be computed to the correct array size with sizeof

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.