如何创建一个动态数组?

我们可以用到malloc函数进行:

#include <stdio.h>  
#include <stdlib.h>  
  
int main() {  
    int size;  
    printf("Enter the size of the array: ");  
    scanf("%d", &size);  
      
    // 使用malloc()函数分配内存空间  
    int *array = (int*)malloc(size * sizeof(int));  #*创建
      
    if (array == NULL) {  
        printf("Error: Memory allocation failed.\n");  
        return 1;  
    }  
      
    // 打印数组中的元素  
    for (int i = 0; i < size; i++) {  
        array[i] = i + 1;  
        printf("%d ", array[i]);  
    }  
    printf("\n");  
      
    // 释放内存空间  
    free(array);  
      
    return 0;  
}

int *array = (int*)malloc(size * sizeof(int));

切记:要有释放空间的做法!

全部评论

相关推荐

Rena1ssanc...:对的,要是面评没太烂,勤更新简历等捞就行了,腾讯可以无限复活
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务