C语言动态数组
原文链接:c语言中动态数组的建立
作者:阿瞒123
一维动态数组的创建,这个比较简单,直接上代码
#define _CRT_SECURE_NO_DEPRECATE #include<stdio.h> #include<stdlib.h> void createOneDimensionalVector(){ int n, i; int *arr; scanf("%d",&n); arr = (int*)malloc(sizeof(int)*n); for (i = 0; i < n; i++) arr[i] = i; for (i = 0; i < n; i++) printf("%d\t",arr[i]); } int main(){ createOneDimensionalVector(); return 0; }
二维动态数组的创建
void createTwoDimensionalVector(){ int n=3, m=4; int** a; a = (int**)malloc(sizeof(int*)*n);//创建一个指针数组,把指针数组的地址赋值给a for (int i = 0; i < n; i++) a[i] = (int*)malloc(sizeof(int)*m);//给第二维分配空间 for (int i = 0; i < n; i++){ for (int j = 0; j < m; j++) a[i][j] = i + j; } for (int i = 0; i < n; i++){ for (int j = 0; j < m; j++) printf("%d\t",a[i][j]); printf("\n"); } } int main(){ createTwoDimensionalVector(); return 0; }