C ++ array initialization Methods

Source: Internet
Author: User

The initialization method of the C ++ array is explained in detail. The data name is an array data structure. In the arrayTest function, str is an array name. Why is the result of sizeof pointer length? This is because:

(1) When the array name is used as a function parameter, In the function body, it loses its own meaning and is just a pointer;

(2) Unfortunately, it also loses its constant feature while losing its connotation. It can perform auto-increment, auto-subtraction, and other operations and can be modified.

 

First look at array Initialization

# Include <iostream>
Using std: cout;
Using std: endl;

# Include <iomanip>
Using std: setw;

Int main ()
{
Int n [10];

For (int I = 0; I <10; I ++)
N [I] = 0;

For (int j = 0; j <10; j ++)
Cout <n [j] <endl;

Return 0;
}

Output result

0
0
0
0
0
0
0
0
0
0


Initialize an array

# Include <iostream>
Using std: cout;
Using std: endl;

# Include <iomanip>
Using std: setw;

Int main ()
{
Int n [10] = {2, 7, 4, 8, 5, 4, 9, 7, 6, 3 };

For (int I = 0; I <10; I ++)
Cout <n [I] <endl;

Return 0;
}


Static array will be initialized to 0

# Include <iostream>
Using std: cout;
Using std: endl;

Void staticArrayInit (void );
Void automaticArrayInit (void );

Int main ()
{
StaticArrayInit ();
AutomaticArrayInit ();

StaticArrayInit ();
AutomaticArrayInit ();
Return 0;
}

Void staticArrayInit (void)
{
Static int array1 [3];

For (int I = 0; I <3; I ++)
Cout <"array1 [" <I <"] =" <array1 [I] <"";

For (int j = 0; j <3; j ++)
Array1 [j] = 0;
}

Void automaticArrayInit (void)
{
Int array2 [3] = {1, 2, 3 };

For (int I = 0; I <3; I ++)
Cout <"array2 [" <I <"] =" <array2 [I] <"";

For (int j = 0; j <3; j ++)
Array2 [j] = 0;
}
 

Result

Array1 [0] = 0 array1 [1] = 0 array1 [2] = 0 array2 [0] = 1 array2 [1] = 2 array
2 [2] = 3 array1 [0] = 0 array1 [1] = 0 array1 [2] = 0 array2 [0] = 1 array2 [1]
= 2 array2 [2] = 3
 

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.