### Using a pointer to track a 2D matrix

Hi guys,

I'm given an assignment to identify numbers in an image with a PGM format. I was given an image class that puts that image values in a 2D array. I'm trying to access through the 2D array and when I hit the first pixel (say 0 or 255), I want a pointer to point to that location. From then on, I'm going to read the next few columns and determine what number it is. Does anyone have any idea on how to do that?

The ImageType class is printed here:
ImageType::ImageType(int tmpN, int tmpM, int tmpQ)
{
int i, j;

N = tmpN;
M = tmpM;
Q = tmpQ;

pixelValue = new int* [N];
for(i=0; i<N; i++) {
pixelValue[i] = new int[M];
for(j=0; j<M; j++)
pixelValue[i][j] = 0;
}
}

and M and N are 320 for 320x320 image and Q is the maximum pixel value which is 255. So now, there's a [320][320] matrix and I need to traverse it with a pointer.

So far, I have this:
void SearchImage(ImageType &image, int *ptr)

If I loop through the whole matrix and increment ptr, will it store that location in the matrix?

Thanks,
So far, I'm writing a search.cpp file that'll do the searching and sets the pointer to where I want it to be. Here's the code, but I'm getting error C2120:

#include <iostream>
#include <fstream>

#include "image.h"

using namespace std;

void search(ImageType &image, int &ptr)
{
int M, N;
int pix;
M = image.M;
N = image.N;
for(int i=0; i<M; i++)
{
for(int j=0; j<N; j++)
{
if (image.getPixelVal(M,N,pix)!=0)
{
ptr++;
}
}
}
}

Any ideas? Thanks.
OK. I spent more time and got it to I think work, but now the pointer is not being updated in main...

Ex:
void search(ImageType &image, int *ptr)
{
int M, N;
int pix;
M = image.M;
N = image.N;
for(int i=0; i<M; i++)
{
for(int j=0; j<N; j++)
{
image.getPixelVal(i,j,pix);
if (pix!=0)
{
ptr++;
}
}
}
}

in main():

int ptr;
search(image, &ptr);
cout << ptr << endl;

But, it seems like the pointer is only incremented inside the function search but not updated in main. Does that mean I have to return something besides void to update the pointer?

Like
int* search(ImageType &image, int *ptr);

and then in main use it as
int ptr;
&ptr = search(image, &ptr);
cout << ptr << endl;

any help is appreciated. Thanks.
Yes, although you can't do:

 ``12`` ``````int ptr; &ptr = search(image, &ptr);``````

I would suggest doing this:

 ``12`` ``````int* ptr = NULL; ptr = search(image);``````

Since you are returning a pointer, you don't need to pass it as a parameter, just increment/return a temporary pointer value.
Topic archived. No new replies allowed.