Sam*_*Sam -7 c++ pointers multidimensional-array
我用C++编写了一段代码.我从搜索引擎结果中获取了第一部分.
1)使用函数定义函数的含义是什么double **filter_2d?我们可以使用指针定义函数吗?
2)我对以下行感到困惑:
double **filt_out = filter_2d(A, 3, 3, B, 2, 1);
Run Code Online (Sandbox Code Playgroud)
它工作不正常,我不明白为什么.
#include <iostream>
#include <stddef.h>
#include <cmath>
#include <fftw3.h>
using namespace std;
void filter_2d(double** image, int width_image, int height_image, double** kernel, int width_kernel, int height_kernel, double *** OutImg)
{
double **output = *OutImg;
int i, j, p, q;
//this is the case of 'full' option selected in matlab
//double **output = (double **)malloc(sizeof(double *)*(width_image + width_kernel - 1));
for (i = 0; i<width_image + width_kernel - 1; i++)
{
output[i] = (double *)malloc(sizeof(double)*(height_image + height_kernel - 1));
}
//for each point in the output
for (i = 0; i<width_image + width_kernel - 1; i++)
{
for (j = 0; j<height_image + height_kernel - 1; j++)
{
output[i][j] = 0;
//kernel(p,q)*image(i-p, j-q)
for (p = 0; p<width_kernel; p++)
{
//avoid unnecessary comparisons
if (i - p < 0)
{
break;
}
else if (i - p < width_image)
{
for (q = 0; q<height_kernel; q++)
{
//idem as above
if (j - q < 0)
{
break;
}
else if (j - q < width_image)
{
output[i][j] += kernel[p][q] * image[i - p][j - q];
}
}
}
}
}
}
}
int main()
{
double ** OutImage = 0;
OutImage = (double **)malloc(sizeof(double *)*(3 * 3));
double A[3][3] = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
double *A_ptr[9];
for (int i = 0; i < 10; i++)
{
A_ptr[i] = A[i];
}
double B[1][2] = { 1, 2 };
double *B_ptr[2];
for (int i = 0; i < 2; i++)
{
B_ptr[i] = B[i];
}
//Error in the below line
filter_2d(A_ptr, 3, 3, B_ptr, 2, 1, &OutImage); //unable to understand
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 4; j++)
cout << *OutImage << endl;
}
system("PAUSE");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
指针声明
一般格式:
data_type *pointer_name;
Run Code Online (Sandbox Code Playgroud)
一个指针声明,如,
int *numberPtr;
Run Code Online (Sandbox Code Playgroud)
将numberPtr声明为指向整数变量的变量.它的内容是一个内存地址.
*表示声明的变量是指针变量而不是普通变量.
请考虑以下声明:
int *numberPtr, number = 20;
Run Code Online (Sandbox Code Playgroud)
在这种情况下,保留了两个存储器地址,与名称numberPtr和number相关联.
变量号中的值是整数类型,变量numberPtr中的值是另一个内存位置的地址.
例
// create a 2D array dynamically
int rows, columns, i, j;
int **matrix;
cin >> rows >> columns;
matrix = new int*[rows];
for(i=0; i<rows; i++)
matrix[i] = new int[columns];
Run Code Online (Sandbox Code Playgroud)