The C language is perfect for dynamic array code sharing

  • 2020-05-09 18:54:25
  • OfStack

As we know, the size of the array in C is fixed, so you have to give it a constant value, not a variable.

This is a big inconvenience, if the array is too small to hold all the arrays, if it's too large, it's a waste of resources.

Please implement 1 simple dynamic array, can change the size at any time, will not overflow, will not waste memory space.

The following code implements a simple dynamic array:


#include <stdio.h>
#include <stdlib.h>
int main()
{
  // Gets the initial array size from the console 
  int N;
  int *a;
  int i;
  printf("Input array length:");
  scanf("%d",&N);
  // Allocate space 
  a=(int *)calloc(N,sizeof(int));
  // Fill in the data 
  for(i=0;i<N;i++){
    a[i]=i+1;
    printf("%-5d",a[i]);
    if((i+1)%10==0){
      printf("\n");
    }
  }
  // Free memory 
  free(a);
  a=NULL;
  printf("\n");
  return 0;
}

Operation results:


Input array length:20
1  2  3  4  5  6  7  8  9  10
11  12  13  14  15  16  17  18  19  20


Related articles: