Dynamic Arrays in C: Handling Unknown Sizes

In C language, dynamic memory allocation can be used to create arrays with an unknown number of inputs. The specific steps are as follows:

  1. Create a dynamic array using pointer variables, like int *arr;.
  2. You can use the malloc function to allocate memory space for an array, which allows you to dynamically allocate space according to the number of elements needed. For example, arr = (int *)malloc(n * sizeof(int)); where n is the number of elements needed to be input.
  3. Use a loop structure to input array elements one by one, for example:
for (int i = 0; i < n; i++) {
    scanf("%d", &arr[i]);
}
  1. Release the memory used by the array.

Here is the complete example code:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int n;
    printf("请输入数组的个数:");
    scanf("%d", &n);

    int *arr;
    arr = (int *)malloc(n * sizeof(int));

    printf("请输入数组元素:\n");
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    printf("输入的数组为:");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    free(arr);
    return 0;
}
bannerAds