When array C is used as the form parameter, this parameter degrades to a pointer.

Source: Internet
Author: User

When an array is used as a function parameter, this parameter degrades to a pointer and cannot be used to directly obtain the array size.

The array is passed to a function. The array type is automatically converted to the pointer type, so the actual address is passed.
Void func (INT array [10])
Void func (INT array [])
Void func (int * array)
Therefore, the above three function declarations are completely equivalent.


The actual situation is that the array is used as a parameter and cannot be passed by value at all. This is determined by the implementation mechanism of C/C ++ functions.

The calculation of the array size is usually as follows:

Int Len = sizeof (ARR)/sizeof (type)

Obtain the length of the Array Based on the relationship between the total length and the length of a single element.

But as the form parameter, the length of sizeof (ARR) is 4, that is, the length of a pointer.

There are two ways to solve this problem:

Method 1.

When passing parameters, add a parameter directly as the length of the array.

Method 2. (incorrect)

Int * P = A [0];
Int ilen = 0;
While (P! = NULL)
{
Ilen ++;
* P ++;
}

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.