What are the different ways to define arrays in the C programming language?

In the C language, arrays can be defined in the following ways:

  1. Define arrays statically: arrays are defined outside functions or in a global scope. Arrays defined in this way are always present during program execution and their size is determined at compile time.
int arr[10]; // 定义一个包含10个整数的数组
  1. Allocate memory
int n;
scanf("%d", &n);
int *arr = (int*)malloc(n * sizeof(int)); // 动态分配n个整数的数组
  1. Static initialization of arrays involves specifying initial values for array elements at the time of defining the array. Arrays initialized in this way have their initial values specified at the time of definition, and their size is also determined during compilation.
int arr[] = {1, 2, 3, 4, 5}; // 定义一个包含5个整数的数组,并初始化为1、2、3、4、5
  1. Dynamic initialization of an array: after defining the array, assign values to each element one by one. This type of array does not have specified initial values at the time of definition and needs to be assigned values individually at runtime.
int arr[5];
for (int i = 0; i < 5; i++) {
    arr[i] = i + 1; // 为数组元素赋值为1、2、3、4、5
}
bannerAds