我需要创建一个包含2D数组的结构,但是数组大小可能会有所不同,所以我不能用常量长度来定义它。我试图用双指针解决这个问题,但发现双指针与双数组不一样。那我怎么能这样做呢?
struct GaussianKernel {
int r;
double weightSum;
double **kernel;
};
GaussianKernel initializeKernel2D(jdouble sigma){
int r = (int) ceil(3 * sigma);
int kernelLen = 2 * r + 1;
double G[kernelLen][kernelLen];
double weightSum = 0;
double temp;
for (int y = -r; y <= r; y++)
{
for (int x = -r; x <= r; x++)
{
temp = exp(-(pow(x, 2) + pow(y, 2)) / (2 * pow(sigma, 2))) / (2 * PI * pow(sigma, 2));
G[y + r][x + r] = temp;
weightSum = weightSum + temp;
}
}
struct GaussianKernel GKernel;
GKernel.r = r;
GKernel.kernel = G;
GKernel.weightSum = weightSum;
return GKernel;
}
答案 0 :(得分:1)
你应该将你的2D动态数组分配为:
GKernel.kernel = malloc(kernelLen * sizeof(double *));
for(i=0;i<kernelLen;i++)
GKernel.kernel[i] = malloc(kernelLen * sizeof(double));
然后,您可以根据程序逻辑将值存储在GKernel.kernel