向结构添加元素时出现分段错误
为什么我在这个函数中遇到分段错误:
#include <stdio.h>
#include <stdlib.h>
#include "math.h"
vec_t mtrx_multiple (sparse_mat_t a, vec_t c) {
vec_t result;
int i;
result.n = a.n;
printf("result.n: %d\n", result.n);
result.vec = malloc(a.n * sizeof *result.vec);
for(i=0; i<a.n; i++)
result.vec[i] = c.vec[i] * a.a[a.ja[i]];
return result;
}
结构是:
typedef struct {
int n;
int *vec;
} vec_t;
typedef struct {
int *a;
int *ia;
int *ja;
int n;
} sparse_mat_t;
感谢帮助
Why do I get segmentation fault in this function:
#include <stdio.h>
#include <stdlib.h>
#include "math.h"
vec_t mtrx_multiple (sparse_mat_t a, vec_t c) {
vec_t result;
int i;
result.n = a.n;
printf("result.n: %d\n", result.n);
result.vec = malloc(a.n * sizeof *result.vec);
for(i=0; i<a.n; i++)
result.vec[i] = c.vec[i] * a.a[a.ja[i]];
return result;
}
The structure is:
typedef struct {
int n;
int *vec;
} vec_t;
typedef struct {
int *a;
int *ia;
int *ja;
int n;
} sparse_mat_t;
Thanks for help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我怀疑问题出在
aa[a.ja[i]]
上,您应该在使用它们索引之前尝试验证值
。a.ja[i]
aa了解
a
是如何初始化的以及段错误发生在哪一行将会很有用。I suspect the problem is with
a.a[a.ja[i]]
, you should try verifying the valuesa.ja[i]
before using them to indexa.a
.It would be useful to know how
a
is initialised, and also on which line the segfault occurs.Malloc 可能会失败并返回 null。
a.ja[i] 可能不在 0 和 n 之间。 ja 数组应该代表什么?
我们的猜测不会得出答案。在调试器下运行您的程序将会。
Malloc could be failing and returning null.
a.ja[i] might not be between 0 and n. What is the ja array supposed to represent, anyway?
Our speculating isn't going to produce the answer. Running your program under a debugger will.
我怀疑这是问题所在的行:
The Reason is that you are notmalloc
ing for everyresult.vec[i]
..你能证实这一点吗?
编辑:
感谢 Alok 和 Devel 告知我我的错误...
sizeof *result.vec
返回什么?不可否认,它看起来很混乱,好像sizeof
之间的优先级与*
混合在一起......希望这会有所帮助,
此致,
汤姆.
I suspect this is the line where the trouble is:
The reason is that you are notmalloc
ing for eachresult.vec[i]
..Can you confirm this?
Edit:
Thanks Alok and Devel for informing me about my error...
What does
sizeof *result.vec
return? Admittedly it looks confusing as if the precedence betweensizeof
gets mixed with the*
...Hope this helps,
Best regards,
Tom.
<代码>
我必须同意 Autopulated,这个版本的代码运行得很好,我在这次重构中唯一遗漏的是 a 和 c 相关的东西。我会检查 a 和 c 是否正确初始化。
I have to agree with Autopulated, this version of your code runs just fine, the only thing I left out in this refactoring is the a and c related stuff. I would check that a and c are being initialized properly.