将随机元素分配给函数中的 int 二维矩阵时,如何避免 C 中的 SIGSEGV 分段错误?
How to avoid SIGSEV Segmentation fault in C when allocating random elements to an int 2D matrix in a function?
我正在做一项作业,我们需要使用数组表示法将随机整数分配给 5x5 矩阵(因此不能在此处使用指针)。看了this closed Stack Overflow non-question后,我写了如下新手代码:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define rows 5
#define cols 5
void fillMatrix(int matrix[rows][cols])
{
srand(time(NULL));
for(int i = 0; i<rows; i++)
for(int j = 0; i<cols; j++)
matrix[i][j] = rand() % 100 + 1;
}
int main()
{
int matrix[rows][cols];
fillMatrix(matrix);
}
SIGSEGV 分段错误发生在
行
matrix[i][j] = rand() % 100 + 1;
根据gdb
。另外,使用 backtrace
我能够看到这个错误来自这里:
(gdb) backtrace
#0 0x0000000000400690 in fillMatrix (matrix=0x7fffffffe7d0) at program.c:13
#1 0x00000000004006d2 in main () at program.c:19
我的理解是,分配的值是寻址内存位置,这些位置未在矩阵中定义,或者根本不允许访问。所以考虑到 backtrace
,这是否意味着我在 main 函数中声明矩阵的方式是错误的?或者我的函数 fillMatrix()
本身在有问题的那一行是错误的?
提前致谢!
你有一个错误。在您的代码中将 "i" 更改为 "j"。
void fillMatrix(int matrix[rows][cols])
{
srand(time(NULL));
for(int i = 0; i<rows; i++)
for(int j = 0; i<cols; j++) << here is a bug
matrix[i][j] = rand() % 100 + 1;
}
我正在做一项作业,我们需要使用数组表示法将随机整数分配给 5x5 矩阵(因此不能在此处使用指针)。看了this closed Stack Overflow non-question后,我写了如下新手代码:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define rows 5
#define cols 5
void fillMatrix(int matrix[rows][cols])
{
srand(time(NULL));
for(int i = 0; i<rows; i++)
for(int j = 0; i<cols; j++)
matrix[i][j] = rand() % 100 + 1;
}
int main()
{
int matrix[rows][cols];
fillMatrix(matrix);
}
SIGSEGV 分段错误发生在
行 matrix[i][j] = rand() % 100 + 1;
根据gdb
。另外,使用 backtrace
我能够看到这个错误来自这里:
(gdb) backtrace
#0 0x0000000000400690 in fillMatrix (matrix=0x7fffffffe7d0) at program.c:13
#1 0x00000000004006d2 in main () at program.c:19
我的理解是,分配的值是寻址内存位置,这些位置未在矩阵中定义,或者根本不允许访问。所以考虑到 backtrace
,这是否意味着我在 main 函数中声明矩阵的方式是错误的?或者我的函数 fillMatrix()
本身在有问题的那一行是错误的?
提前致谢!
你有一个错误。在您的代码中将 "i" 更改为 "j"。
void fillMatrix(int matrix[rows][cols])
{
srand(time(NULL));
for(int i = 0; i<rows; i++)
for(int j = 0; i<cols; j++) << here is a bug
matrix[i][j] = rand() % 100 + 1;
}