在這裏做一些事情(或許多事情)是錯誤的,但不能完全弄明白。函數需要創建一個用戶定義的二維數組並返回一個指向該數組的指針。使用函數初始化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);
任何幫助非常感謝!由於
你錯過了間接的在你的基地指針數組的水平。一旦你解決了這個問題,你的免費操作將需要釋放每一行。請將您的malloc與免費遊戲匹配。 [請參閱此問題](http://stackoverflow.com/a/13732378/1322972)以瞭解如何執行此操作的示例。最後,[在C編程時不要投入malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc)。 – WhozCraig
感謝您的建議,讓它像上面的例子一樣運行! – user3289715