对于已编码的简单函数,发生分段故障错误 [英] Segmentation fault error occurs for a simple function I have coded
问题描述
这里我只想定义一个返回矩阵乘法的函数, N
任意,我想生成一个 new
命令。当我执行该函数时,我得到错误:
Here I just want to define a function which returns the multiplication of matrices, with N
arbitrary, I would like to generate a matrix with a new
command. When I execute the function I get the error:
Segmentation fault (core dumped)
每当我为 C
赋值时,我就有这个错误,任何人都能告诉我发生了什么,如何修复它?
Whenever I assign values to C
I have this error, could anybody tell me what happened and how to fix it?
int **multiply(int **A, int **B, int N){
int **C = new int*[N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
for (int k = 0; k < N; k++)
C[i][j] = C[i][j] + A[i][k] * B[k][j];
}
}
return (C);
}
推荐答案
int **C=new int*[N];
这会为指针数组创建空间。它不会初始化它们,所以他们可以指向任何地方。它们可能是NULL指针。
This makes space for an array of pointers. It doesn't initialize them, so they could point anywhere. They might even be NULL pointers.
C[i][j]
这可能会导致空指针取消引用。这可能是造成分段错误的原因。
This might cause a null pointer dereference. That's probably what causes the segmentation fault.
这篇关于对于已编码的简单函数,发生分段故障错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!