Dankevich Dankevich - 3 months ago 9
C++ Question

Pointer to array of structs element field in a function

I have a function which searches for extrema in some data array. It takes pointer to data, some parameters and a pointer to struct array where the result is stored. The function returns the length of the resulting struct array.

int FindPeaks(float *data, int WindowWidth, float threshold, struct result *p)
{
int RightBorder = 0;
int LeftBorder = 0;

bool flag = 1;

int i = 0;
int k = 0;

while(1)
{
flag = 1;
if (WindowWidth >= 200) cout << "Your window is larger than the signal! << endl";
if (i >= 200) break;
if ((i + WindowWidth) < 200) RightBorder = i + WindowWidth;
if ((i - WindowWidth) >= 0) LeftBorder = i - WindowWidth;
for(int j = LeftBorder; j <= RightBorder; j ++)
{
if (*(data + i) < *(data + j))
{
flag = 0;
break;
}
}
if (flag && *(data + i) >= threshold && i != 0 && i != 199)
{
struct result pointer = p + k;
pointer.amplitude = *(data + i);
pointer.position = i;
i = i + WindowWidth;
k++;
}
else
{
i ++;
}
}

return k;
}


I'm confused with a reference to i-th struct field to put the result in there. Am I doing something wrong?

Answer

You're trying to be too smart with use of pointers, so your code won't even compile.

Instead of using *(data + i) or *(data+j) everywhere, use data[i] or data[j]. They're equivalent, and the second is often more readable when working with an array (assuming the data passed by the caller is actually (the address of the first element of) an array of float).

The problem you asked about is this code

struct result pointer = p + k;
pointer.amplitude = *(data + i);
pointer.position = i;

where p is a pointer to struct result passed to the function as argument. In this case, pointer actually needs to be a true pointer. Assuming you want it to point at p[k] (rather than creating a separate struct result) you might need to do

struct result *pointer = p + k;    /*   equivalently &p[k] */
pointer->amplitude = data[i];
pointer->position = i;

This will get the code to compile. Note that you have not described what the function is actually supposed to achieve, so I have not bothered to check if the code actually does anything sensible.

Note that you're actually (mis)using C techniques in C++. There are much better alternatives in modern C++, such as using standard containers.