首页 > 其他分享 >动态创建数组,一维和二维

动态创建数组,一维和二维

时间:2022-10-21 16:33:18浏览次数:47  
标签:arr int 二维 动态创建 ++ 维和 malloc printf sizeof


#include<stdio.h>
#include<stdlib.h>
void OneDimensionVector(){ //用来创建一维数组
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",arr[i]);
}

二维:

void TwoDimensionVector(){               //二维
int m,n,i,j,k=0;
int** arr;
scanf("%d%d",&m,&n);
arr = (int**)malloc(sizeof(int*)*m);//创建一个指针数组,把指针数组的地址赋值给a
for (i = 0; i < m; i++)
arr[i] = (int*)malloc(sizeof(int)*n);//给第二维分配空间

for (i = 0; i < m; i++){
for ( j = 0; j < n; j++)
arr[i][j] = k++;
}

for (i = 0; i < m; i++){
for (j = 0; j < n; j++)
printf("%d",arr[i][j]);
printf("\n");
}
}
int main()
{
TwoDimensionVector();
return 0;
}


标签:arr,int,二维,动态创建,++,维和,malloc,printf,sizeof
From: https://blog.51cto.com/u_15840342/5783650

相关文章