我在 Eclipse/C 中遇到了奇怪的行为。我声明了以下类型,比方说,啊。
typedef double sig_type[3];
和下面的,比方说,b.c
typedef struct filter_kind {
. . .
sig_type * fil_buff; //The buffer for all values
. . .
} filter_kind;
int init_filter(filter_kind * filter, const sig_type init_data[],
const int data_len) {
if (filter->data_buff_len != data_len) {
return -1
}
int i;
int j;
for (i = 0; i < filter->data_buff_len; i++) {
for (j = 0; j < OUT_NUM; j++) {
(filter->fil_buff)[i][j] = init_data[i][j]; //prog exits on this line.
}
}
filt_coeffs(filter);
return 0;
}
我有一个指定的函数返回指向一个 malloc 的 filter_kind 结构的指针,它 mallocs fil_buff。当我使用这个创建函数,并将新创建的 filter_kind 指针传递给 init_filter 时,该函数在分配给 (filter->fil_buff)[][] 时意外退出——调试 View 中除了“gdb”外几乎没有其他注释。
我放入了一些探测变量,并在调试期间查看了它们,到目前为止似乎没有任何异常。我可以很好地从数组中读取,只是无法分配。我在这里做错了什么吗?
最后,这里是构造函数和相应的分配函数。
filter_kind * create_filter(const double f_lo, const double f_hi,
const double samp_r, win_type window_t, fil_type filter_t,
const int buff_len) {
filter_kind * filter;
sig_type * fil_buff;
int err = 0;
/* allocate filter struct */
filter = (filter_kind *) malloc(sizeof(filter_kind));
err = (filter != NULL ) ? 0 : -1;
if (err == -1) {
return NULL ;
}
memset(filter, 0, sizeof(filter_kind));
/* allocate filter data members */
err = alloc_buffs(win_coeffs, fil_coeffs, fil_buff, buff_len);
if (err == -1) {
return NULL ;
}
//assign other structure values...
filter->fil_buff = fil_buff;
return filter;
}
static int alloc_buffs(double * win_coeffs, double * fil_coeffs,
sig_type * fil_buff, const int buff_len) {
int err = 0;
//allocate other buffers...
err = alloc_st_buff(fil_buff, buff_len);
if (err == -1) {
return -1;
}
return 0;
}
static int alloc_st_buff(sig_type * st_buff, const int buff_len) {
const int num_bytes = sizeof(sig_type) * buff_len;
st_buff = (sig_type *) malloc(num_bytes);
const int err = (st_buff != NULL ) ? 0 : -1;
if (err == -1) {
return -1;
}
memset(st_buff, 0, num_bytes);
return 0;
}
以及它的值(value),旨在按如下方式使用
filter_kind * filter;
filter = create_filter(...);
/* Load data into array of sig_type, i.e. sig_type arr[40] */
init_filter(filter, arr, 40);
/* more code... */
最佳答案
好的问题是分配缓冲区(调用分配函数):
sig_type * fil_buff;
err = alloc_buffs(win_coeffs, fil_coeffs, fil_buff, buff_len);
filter->fil_buff = fil_buff;
那么这里发生了什么:
- 创建指向名为
fil_buff
的表的指针, - 使用 副本 指向
fil_buff
等的指针调用函数 alloc_buffs, - 将 not changed
fil_buff
分配给一个结构。
每次函数接受参数时,它都会生成一个副本。所以当你传递一个指针时,函数会复制这个指针(并且它正在操作指针的副本),因此原始指针(在函数调用之前)不会改变。您应该将指针传递给要操作的指针。可以这样做的方法是:
err = alloc_buffs(win_coeffs, fil_coeffs, &fil_buff, buff_len);
^^^^^^^^^
那么您的 fil_buff
确实可以更改,但是您必须调整您的函数以采用适当的参数并对其进行适当的操作。我想其他缓冲区也犯了同样的错误。
关于c - Eclipse 在分配 2D 数组元素期间无消息终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32596534/