[英]Segmentation fault in passing multidimensional arrays to functions in C
在我的簡介中,我們看到了使用指針將數組傳遞給函數的信息。 到C類,我正在嘗試學習如何自行傳遞多維數組。 我嘗試編寫一個函數以將矩陣的項的值分配給本地數組,但是遇到了分段錯誤。 我希望有人能夠解釋為什么會發生這種情況以及如何解決。 我在macOS Sierra上使用終端。 提前致謝。 我的代碼如下:
#include <stdio.h>
#include <stdlib.h>
void fillMatrix();
int main(void){
int rows, cols;
printf("\nEnter the number of columns:\n");
scanf("%d", &cols);
printf("\nEnter the number of rows:\n");
scanf("%d", &rows);
int matrix[rows][cols];
fillMatrix(&matrix[rows][cols], rows, cols);
for (int i = 0; i < rows; ++i){
for (int j = 0; j < (cols - 1); ++j){
printf("%d ", matrix[i][j]);
} printf("%d\n", matrix[i][(cols -1)]);
}
return 0;
}
void fillMatrix( int *matrix, int rows, int cols ){
for (int i = 0; i < rows; ++i){
for (int j = 0; j < cols; ++j){
printf("\nPlease enter the A(%d,%d) entry:\n", i, j);
scanf("%d", &*(matrix + (i*cols) + j));
}
}
return;
}
給出聲明
int matrix[rows][cols];
這段代碼是錯誤的:
fillMatrix(&matrix[rows][cols], rows, cols);
&matrix[rows][cols]
的地址在&matrix[rows][cols]
的末尾。
矩陣的第一個元素是&matrix[0][0]
,矩陣的最后一個元素是&matrix[rows-1][cols-1]
。
另外,這個聲明
void fillMatrix();
將導致與此定義有關的問題:
void fillMatrix( int *matrix, int rows, int cols ){
...
他們需要匹配。 現在,由於最上面的void fillMatrix()
聲明,參數通過默認參數提升被傳遞給函數,但是由於定義具有顯式參數,因此函數本身希望將參數作為int *
或int
傳遞。 您可能對此沒有任何問題,因為這些參數的默認值可能與那些參數相同,但函數定義和聲明通常必須完全匹配。
我尚未檢查您的代碼是否存在其他問題。
在C中,當您聲明數組時,需要在編譯時指定其大小。 當您使陣列減速時
int matrix[rows][cols];
您實際上是使用垃圾值來初始化其大小的。 對於我的編譯器,它的大小為[0] [0]初始化。 為了實現您想要的目標,您需要執行以下兩項操作之一:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.