新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

c语言中动态数组如何创建,c语言中动态数组的创建

发布时间:2023-11-29 18:59:12

c语言中动态数组如何创建

在C语言中,可以通过malloc函数还是calloc函数来创建动态数组。

  1. 使用malloc函数创建动态数组:
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr;
    int size;

    printf("Enter the size of the array: ");
    scanf("%d", &size);

    arr = (int *)malloc(size * sizeof(int));
    
    if (arr == NULL) {
        printf("Memory allocation failed!
");
        return 0;
    }

    printf("Enter the elements of the array:
");
    for (int i = 0; i < size; i++) {
        scanf("%d", &arr[i]);
    }

    printf("The elements of the array are:
");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("
");

    free(arr);

    return 0;
}
  1. 使用calloc函数创建动态数组:
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr;
    int size;

    printf("Enter the size of the array: ");
    scanf("%d", &size);

    arr = (int *)calloc(size, sizeof(int));
    
    if (arr == NULL) {
        printf("Memory allocation failed!
");
        return 0;
    }

    printf("Enter the elements of the array:
");
    for (int i = 0; i < size; i++) {
        scanf("%d", &arr[i]);
    }

    printf("The elements of the array are:
");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("
");

    free(arr);

    return 0;
}

不管是使用malloc或calloc函数创建动态数组,都需要注意释放内存的操作,可使用free函数释放动态数组占用的内存空间。