我将 xcode 与 c 一起使用,但下面的代码有一个奇怪的问题。
当算法到达我的 conv 函数中的 y[k] = 0.0 行时,x 数组被 0-s 填充,我必须明白为什么,我已经以自己的方式纠正了这个错误。当我在主函数中注释第二行并取消注释第三行时,问题没有出现(见下文)。我知道我在 generateSquareSignal 中重新分配了数组,但这不是我认为这个错误的原因。
int length = 100;
double *output = (double*) malloc(10 * length * sizeof(double));
//double *output;
output = generateSquareSignal(length);
double *input1 = (double*) malloc(length * sizeof(double));
double *input2 = (double*) malloc(length * sizeof(double));
for (int i = 0; i < length; i++) {
input2[i] = output[i];
input1[i] = output[i];
//printf("-%d=%lf\n",i ,input1[i]);
}
conv(input1, length, input2, length, output, 2 * length );
double* generateSquareSignal(int length) {
printf("double* generateSquareSignal(int length)\n");
double *signal = (double*) malloc(length * sizeof(double));
int length_period = length / kPeriodSignal;
for(int i=0; i < length; i++) {
if (i % (length_period) < (length_period / 2)) {
signal[i] = 1.0;
} else {
signal[i] = -1.0;
}
//printf("%d. - %lf\n", i, signal[i]);
}
return signal;
}
void conv( double *x, int N_signal,
double *h, int N_kernel,
double *y, int N_output) {
int k;
for(k = 0; k < N_signal + N_kernel; k++) {
y[k] = 0.0;
}
for (int i = 0; i < N_signal; i++) {
printf("%lf-%lf\n", x[i], y[i]);
}
for(int i = 0; i < N_signal; i++) {
for(int j = 0; j < N_kernel; j++) {
double xx = x[i];
double hh = h[j];
double yy = y[i + j];
y[i + j] += x[i] * h[j];
//printf("=%lf\n", y[i + j]);
}
}
}