【发布时间】:2010-01-20 23:26:42
【问题描述】:
为什么我在这个函数中会出现分段错误:
#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;
感谢您的帮助
【问题讨论】:
-
你在哪一行得到段错误?您的索引很可能超出范围。
a.a等有没有用处? -
结构中的一些有用的变量名将有助于提高这一点的可读性。
-
a是由测试函数使用其他函数生成的。它运作良好。a.a和j.a具有a.n元素。 -
另外,您检查过您的
malloc()返回值吗?您可能会向其传递大量数字,并且/或者内存不足。 -
n究竟应该代表什么?
标签: c malloc segmentation-fault