C + + code: Array initialization

Source: Internet
Author: User

An array definition with initialization, the number of elements can be omitted, that is, the expression in square brackets can be omitted. At this point, the number of elements that are finalized depends on the number of initialized values. For example:

1#include <iostream>2 using namespacestd;3 intMain ()4 {5     intA[] = {1,2,3,4,5};6      for(inti =0; I <sizeof(a)/sizeof(a[0]); ++i)7cout << A[i] <<" ";8cout <<"\ n";9Cin.Get();Ten     return 0; One}

Operation Result:

In the program, sizeof (a) is used, that is, the number of bytes in the A array. There is also sizeof (a[0]), which is the number of bytes of space occupied by the first element, because it is a shaped array, so it is equivalent to sizeof (int), and the number of degrees in the 32-bit compiler is 4. A array has several elements, each of which has sizeof (A[0]) bytes, so dividing the two is the number of elements. This expression is intended to be maintainable. (because the number of array elements may also change as programming needs occur.) In a slightly larger programming, the input process is often separated from the processing process, that is, there are many statements in the middle, so it is not immediately possible to visually see the value of the number of array elements, and according to the array name and its elements of information, the way to get the number of elements, with good versatility. The structure description of the For loop does not have to be changed with the initialization of the array)

C + + code: Array initialization

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.