c语言中动态数组怎么创建

   2025-02-13 3890
核心提示:在C语言中,可以通过malloc函数或者calloc函数来创建动态数组。使用malloc函数创建动态数组:#include stdio.h#include stdlib.h

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

使用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!\n");        return 0;    }    printf("Enter the elements of the array:\n");    for (int i = 0; i < size; i++) {        scanf("%d", &arr[i]);    }    printf("The elements of the array are:\n");    for (int i = 0; i < size; i++) {        printf("%d ", arr[i]);    }    printf("\n");    free(arr);    return 0;}
使用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!\n");        return 0;    }    printf("Enter the elements of the array:\n");    for (int i = 0; i < size; i++) {        scanf("%d", &arr[i]);    }    printf("The elements of the array are:\n");    for (int i = 0; i < size; i++) {        printf("%d ", arr[i]);    }    printf("\n");    free(arr);    return 0;}

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

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言