0
A
回答
0
1
你可能會想使用該動態內存分配,在這種情況下,你可以使用雙指針的值。此外,不要將尺寸全部傳遞給該地方,您可以爲矩陣製作一個struct
。例如:
#include <stdio.h>
#include <stdlib.h>
struct matrix_t {
int width;
int height;
int** values;
};
matrix_t* alloc_matrix(int width, int height) {
int i;
matrix_t* matrix;
matrix = (matrix_t*)malloc(sizeof(matrix_t));
matrix->width = width;
matrix->height = height;
matrix->values = (int**)malloc(sizeof(int*) * height);
for (i = 0; i < height; ++i) {
matrix->values[i] = (int*)malloc(sizeof(int) * width);
}
return matrix;
}
void free_matrix(matrix_t* matrix) {
int i;
for (i = 0; i < matrix->height; ++i) {
free(matrix->values[i]);
}
free(matrix->values);
free(matrix);
}
void matrix_func(matrix_t* x) {
int row;
int col;
for (row = 0; row < x->height; ++row) {
for (col = 0; col < x->width; ++col) {
printf("%d ", x->values[row][col]);
}
printf("\n");
}
}
int main() {
int height;
int width;
matrix_t* matrix;
printf("Enter height: ");
scanf("%d", &height);
printf("Enter width: ");
scanf("%d", &width);
matrix = alloc_matrix(width, height);
matrix_func(matrix);
free_matrix(matrix);
}
輸出示例:
Enter height: 4
Enter width: 5
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
+0
而不是'matrix =(matrix_t *)malloc(sizeof(matrix_t));',考慮'matrix = malloc(sizeof * matrix);'更容易正確編碼,查看和維護。 – chux
相關問題
- 1. 將固定尺寸的本徵矩陣作爲參數傳遞給函數調用動態大小的矩陣
- 2. 如何用用戶指定的尺寸創建矩陣
- 3. 尺寸()返回1,其中矩陣尺寸不應該存在
- 4. 確定矩陣尺寸
- 5. C中矩陣的尺寸
- 6. Matlab矩陣尺寸
- 7. 矩陣尺寸matlab
- 8. 其他...索引超過矩陣尺寸
- 9. matlab和矩陣的尺寸
- 10. 傳遞數組函數:陣列必須具有「尺寸」型
- 11. 陣列對象的尺寸傳遞給函數
- 12. 如何從矩陣保持其尺寸在Matlab
- 13. 如何使用S函數在Simulink中傳遞矩陣
- 14. 基於系統矩陣的自定義傳遞函數
- 15. Excel的VBA - 用戶自定義函數 - 可變尺寸參數
- 16. Matlab矩陣旋轉,尺寸
- 17. 矩陣尺寸誤差
- 18. 變化矩陣尺寸
- 19. 操縱矩陣尺寸
- 20. 乘以特定尺寸矩陣
- 21. 在CUDA內核中使用很多固定尺寸的矩陣
- 22. 在傳遞函數矩陣(C)
- 23. 傳遞矩陣函數在python
- 24. 如何比較1xN結構數組中的矩陣尺寸
- 25. MATLAB如果函數和,矩陣尺寸必須同意錯誤
- 26. R中矩陣的最大尺寸
- 27. MATLAB中的矩陣尺寸錯誤
- 28. 尋找在不同尺寸的矩陣
- 29. 如何將值傳遞給XSLT中的用戶定義函數
- 30. R:應用功能在矩陣和保持矩陣尺寸
size參數應該是第一參數:'空隙Matrix_func(INT大小,INT X [大小] [大小])' – mch