Determine whether the length of an array is length or sizeof?

Source: Internet
Author: User
Recently I found some Code And even some expert code, the length of the array used when traversing the array turns out to be sizeof (ARR); this is not suitable!

If it is a one-dimensional array and the element size is a byte, no error is displayed, for example:

 
VaR arr1: array [0 .. 9] of char; arr2: array [0 .. 9] of byte; begin showmessagefmt ('% d, % d', [length (arr1), sizeof (arr1), length (arr2 ), sizeof (arr2)]); {display result: 10, 10, 10} end;

  

However, if the array element contains more than one byte or multi-dimensional array, it will not work. For example:

Const arr1: array [0 .. 9] of integer = (,); arr2: array [0 .. 1, 0 .. 3] of integer = (1, 2, 3, 4), (5, 6, 7, 8); var arr3: array [Boolean] of integer; arr4: array [byte] of integer; begin showmessage (inttostr (length (arr1); {10} showmessage (inttostr (sizeof (arr1); {40} showmessage (inttostr (length (arr2 ))); {2} showmessage (inttostr (length (arr2 [0]); {4} showmessage (inttostr (length (arr2 [1]); {4} showmessage (inttostr (sizeof (arr2); {32} showmessage (inttostr (length (arr3 ))); {2} showmessage (inttostr (sizeof (arr3); {8} showmessage (inttostr (length (arr4 ))); {256} showmessage (inttostr (sizeof (arr4); {1024} end;

  

We can use this principle to quickly know the total number of elements in a multi-dimensional array:

 const arr: array [0 .. 1, 0 .. 2, 0 .. 3] of integer = ), (6, 6, 6); begin showmessage (inttostr (sizeof (ARR) Div sizeof (integer); {24} end;

   

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.