Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - How to add the number of array members with C language code
How to add the number of array members with C language code
There are two kinds of arrays in C language: dynamic arrays and static arrays.

1 static array.

For static arrays, the number of array members cannot be increased.

So we must first define an array large enough, and then we can use an integer variable to maintain the existing number of members in the array, and then dynamically increase the actual number of members.

take for example

int? a[ 1000];

int? n? =? 0;

while(scanf("%d ",& ampa[n])? ! =? EOF)? n? ++; Such code can achieve a similar effect of increasing the number of array members. N is the actual number of members.

2 dynamic array.

Dynamic arrays can change the number of array members at any time. However, in order to determine the number of the current array, it is necessary to use two integer variables to store the maximum number of members and the existing number of members, so that it can be expanded when it is not enough.

int? n? =? 0,? Size? =? 100; ? //n is the current number of elements, and size is the array size, initially 100.

int? *a? =? NULL// array pointer.

Answer? =? (int? *)malloc(sizeof(int)? *? Size); ? //? Initially allocate 100 elements.

while(scanf("%d ",& ampa[n])? ! =? EOF)?

{

n++;

If (n? & gt=? Size)// Not enough space.

{

Size+=100; //Increase the space of 100 elements.

Answer? =? (int? *)realloc(sizeof(int)*size,? a); //Redistribute space.

}

}