2014-04-10 49 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

你是對的!我的錯。 –