Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - How does C language use variable definitions to arrange the number of elements?
How does C language use variable definitions to arrange the number of elements?
In C language, the dimension of an array represents the number of elements in the array. In a regular array, you must specify a dimension. If not specified, the initial value must be given in the initialization list. The compiler determines the dimension of the array by initializing the list.

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

Although the above code does not specify the dimension of the array, the compiler knows that the dimension of array A is 4 (only 4 elements).

To define the number of elements in an array through variables, that is, dimensions, you can use malloc () and free () for dynamic memory allocation. The following is an example of using dynamic memory:

# Contains? & ltstdio.h & gt

# Contains? & ltmalloc.h & gt

# Contains? & ltstdlib.h & gt

# Contains? & ltstring.h & gt

int? Master ()

{

int? Size;

Printf ("Enter the number of elements to create:");

Scanf("%d ",& size);

int? *p? =? (int? *)malloc(sizeof(int)? *? Size);

What if? (p? ==? 0)? {

Printf ("Unable to allocate memory \ n");

Return? 0;

}

//Initialize memory

memset(p,? 0x00,? sizeof(int)? *? Size);

//Free memory

Free (p);

Return? 0;

}