int **a,i;
int m,n;
a=(int**)malloc(m*sizeof(int));
for(i=0;i<m;i++)
a=(int*)malloc(n*sizeof(int));
就是老师要我们设计个程序中,涉及到很多未知大小的数组,是不是可以把上面的代码放到自定的函数中去,通过调用来实现动态空间的开辟。
主要是数组太多,我不想一个一个的开辟,想就通过m,n赋值后直接实现。
请大神指教啊!!
如果不可以放在函数里【貌似是不可以,直接放进去,我试运行了下,出错了额
那有什么办法实现我说的,通过赋值m,n,然后调用函数来开辟的。
额 说的有点乱 请谅解
当然可以
[mw_shl_code=c,true]int** alloc_memory_for_2D_array(int m, int n){
int **ptr;
int i;
ptr = (int **)malloc(m*sizeof(int *));
for (i=0; i<m; i++){
ptr = (int *)malloc(n*sizeof(int));
}
return ptr;
}[/mw_shl_code]
例子:
[mw_shl_code=c,true]int **array_2d;
const int width = 10;
const int height = 20;
array_2d = alloc_memory_for_2D_array(height, width);
if (array_2d == NULL){
printf("Fail to allocate memory.");
}[/mw_shl_code]
一定不要忘记检查分配是否成功
最后还要有个函数负责free
[mw_shl_code=c,true]void free_memory_for_2D_array(int **ptr, int m){
int i;
for (i=0; i<m; i++){
if (ptr){
free(ptr);
ptr = NULL;
}
}
if (ptr){
free(ptr);
ptr = NULL;
}
}[/mw_shl_code]
[查看全文]
你这样做的a,里面存的是指向数组的指针,所以m为数组个数,然后n是每个数组的大小,这样就可以定义出一个二维数组了,举个例子:
[mw_shl_code=c,true]#include <stdio.h>
#include <stdlib.h>
int main(){
int **a = NULL;
a = (int**)malloc(10 * sizeof(int*));
int i = 0, j = 0;
for(i = 0; i < 10; i++){
a = (int*)malloc((i + 1) * sizeof(int));
}
for(i = 0; i < 10; i++){
for(j = 0; j < i + 1; j++){
a[j] = i;
}
}
for(i = 0; i < 10; i++){
for(j = 0; j < i + 1; j++){
printf("%d ", a[j]);
}
printf("\n");
}
}
[/mw_shl_code]
[查看全文]
