2014-04-10 51 views
0

在这里做一些事情(或许多事情)是错误的,但不能完全弄明白。函数需要创建一个用户定义的二维数组并返回一个指向该数组的指针。使用函数初始化c中动态分配的二维数组

int *create_array (int n, int m, int intitial_value){ 
int *array; 
int index, count; 

array=(int *) malloc(n*sizeof(int));   //allocate memory based on user input 
    for (index=0;index<n;index++){ 
     array[index]=(int *) malloc(m*sizeof(int)); 
    } 


    for (index=0;index<n;index++){ 
     for (count=0;count<m;count++){ 
      array[n][m]=intitial_value; 
     } 
    } 

return *array; 
} 

也好奇我是否正确地从主要释放内存?

ptr=create_array (n, m, intitial_value); 
free(ptr); 

任何帮助非常感谢!由于

+0

你错过了间接的在你的基地指针数组的水平。一旦你解决了这个问题,你的免费操作将需要释放每一行。请将您的malloc与免费游戏匹配。 [请参阅此问题](http://stackoverflow.com/a/13732378/1322972)以了解如何执行此操作的示例。最后,[在C编程时不要投入malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc)。 – WhozCraig

+0

感谢您的建议,让它像上面的例子一样运行! – user3289715

回答

1
int **create_array (int n, int m, int intitial_value){ 
int **array; 
int index, count; 

array = malloc(n*sizeof(int*));   //allocate memory based on user input 
    for (index = 0; index < n; index++){ 
     array[index] = malloc(m*sizeof(int)); 
    } 


    for (index = 0; index < n; index++){ 
     for (count = 0; count < m; count++){ 
      array[index][count] = intitial_value; 
     } 
    } 

return array; 
} 

这样的:

ptr=create_array (n, m, intitial_value); 
free(ptr); 

应该

int i; 
for(i = 0; i < n; i++) { 
    free(ptr[i];) 
} 
free(ptr); 
+1

不应该是'array = malloc(n * sizeof(int *));'?!使用'int *'而不是'int'。 – GoldRoger

+0

你是对的!我的错。 –