Initialization of arrays in C language

Source: Internet
Author: User

In the C language, the initialization of an array is in the following ways:

1. Initialize at the same time as defined:

int array[10] = {1,2,3,4,5};

2. Do not specify the size of the array at the time of definition, by initializing the array elements to determine the size:

int array[] = {1,2,3,4,5};

3. Define the variable and initialize it. Note: The size of the array must be set when defining the variable. You can only assign values to the member elements of the group variables at this time, and cannot be assigned in bulk.

int array[]; Error usage

int array[12];

Array = {1, 2, 3}; Error usage.

Array[0] = 1;

ARRAY[1] = 2;

ARRAY[2] = 3;

4. There is only one case in which the size of the array can be unspecified when it is the formal parameter of the method. This is the first address of the array, so the array length cannot be obtained inside the method, and the array length must be passed as a parameter to the function.

void Test ()

{

int array[] = {1,2,3,4,5};

int length = sizeof (array)/sizeof (int);

int result = Sumofarray (array, length);

printf ("%d", result);

}

int Sumofarray (int array[], int length)

{

int result = 0;

for (int i=0; i<length; i++)

{

Result + = Array[i];

}

return result;

}

Initialization of arrays in C language

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.