问题
This is my code for finding the convolution of two signals but my output is becoming zero everytime can anyone explain the mistake in my code? I tried compling it but I'm unable to findout what is the problem my whole code is correct thanks in advance
#include<stdio.h>
#include<stdlib.h>
#define array_len(x) (sizeof(x)/sizeof(double))
void convolution(double *signal, int nt, double *wind, int r, double *rm)
{
int i,j;
printf("%u\n", sizeof(wind));
int l = (nt+r-1);
for(i=r;i<=l;i++)
{
wind[i]=0;
}
for(i=nt;i<=l;i++)
{
signal[i]=0;
}
printf("signal\n");
for(i=0; i<=l; i++)
{
printf("%lf\n",signal[i]);
}
for(i=0;i<=l;i++)
{
rm[i]=0;
for(j=0;j<=i;j++)
{
rm[i] = (rm[i]+(signal[j]*wind[i-j]) );
}
}
}
void main()
{
double a[] = {1,2,3,4};
int i;
int la = array_len(a);
printf("\nc1\t%ld",la);
double b[] = {1,1,1,1} ;
int lb = array_len(b);
printf("\nc2\t%ld\n",lb);
double r[la+lb-1];
int lr = array_len(r);
printf("\nc3\t%ld\n",lr);
printf("entering convolution\n");
convolution(a,la,b,lb,r);
for(i=0;i<(lr);i++)
{
printf("rm[%d]=%lf\n",i,r[i]);
}
}
回答1:
You try this!
void convolution(double *signal, int nt, double *wind, int r, double *rm)
{
int i,j;
printf("%u\n", sizeof(wind)); // Why you do this? this just returns the size of the pointer only
int l = (nt+r-1);
double one[l];
double two[l];
for(i=0;i<l;i++)
{
if (i < nt)
one[i] = signal[i];
else
one[i] = 0;
if (i < r)
two[i] = wind[i];
else
two[i] = 0;
}
printf("signal\n");
for(i=0; i<l; i++)
printf("%lf\n",one[i]);
for(i=0;i<l;i++)
{
rm[i]=0;
for(j=0;j<=i;j++)
{
rm[i] = (rm[i]+(one[j]*two[i-j]) );
}
}
}
回答2:
May be not a answer to why you see 0 as answer but,
for(i=r;i<=l;i++)
{
wind[i]=0;
}
for(i=nt;i<=l;i++)
{
signal[i]=0;
}
length variable 'l' is (nb+r-1) i.e. 7, while array passed to convolution function, ´b´ and 'a' has only 4 elements and memory is assigned only to accommodate only 4 elements. So with your code you are crossing array boundary for wind and signal. I wonder why is it not crashing.
来源:https://stackoverflow.com/questions/16770078/what-is-the-mistake-in-this-program