Linux c program-array, malloc

Source: Internet
Author: User

# Include <stdio. h>
# Include <stdlib. h>

Struct flex
{
Int count;
Double average;
Double scores []; // defines a scalable Array
}; // Declare the struct

Void showFlex (const struct flex * p); // defines the Function

Int main (void)
{
Struct flex * pf1, * pf2;

Int n = 5; // variable Initialization
Int I;
Int tot = 0;
// Allocate space for structure plus array
Pf1 = malloc (sizeof (struct flex) + n * sizeof (double); // apply for address space based on the array size
Pf1-> count = n;
For (I = 0; I <n; I ++)
{
Pf1-> scores [I] = 20.0-I; // assign a value to the array element
Tot + = pf1-> scores [I];
}
Pf1-> average = tot/n;
ShowFlex (pf1 );

N = 9;
Tot = 0;
Pf2 = malloc (sizeof (struct flex) + n * sizeof (double ));
Pf2-> count = n;
For (I = 0; I <n; I ++)
{
Pf2-> scores [I] = 20.0-I/2.0;
Tot + = pf2-> scores [I];
}
Pf2-> average = tot/n;
ShowFlex (pf2 );
Free (pf1); // release the address space
Free (pf2 );
Return 0;
}

Void showFlex (const struct flex * p) // traverses the array in the struct and prints the average value.
{
Int I;
Printf ("Scores :");
For (I = 0; I <p-> count; I ++)
Printf ("% g", p-> scores [I]);
Printf ("\ nAverage: % g \ n", p-> average );
}

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.