[英]Pointer to array of structs element field in a function
我有一個在某些數據數組中搜索極值的函數。 它需要指向數據的指針,一些參數以及指向存儲結果的struct數組的指針。 該函數返回結果結構數組的長度。
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個struct字段的引用感到困惑,無法將結果放入其中。 難道我做錯了什么?
您正在嘗試使用指針來提高智能,因此您的代碼甚至無法編譯。
不要在各處使用*(data + i)
或*(data+j)
,而要使用data[i]
或data[j]
。 它們是等效的,使用數組時,第二個通常更易讀(假設調用者傳遞的data
實際上是float
數組(的第一個元素的地址))。
您問的問題是此代碼
struct result pointer = p + k;
pointer.amplitude = *(data + i);
pointer.position = i;
其中p
是指向作為struct result
傳遞給函數的struct result
的指針。 在這種情況下, pointer
實際上需要是一個真實的指針。 假設您希望它指向p[k]
(而不是創建單獨的struct result
),則可能需要執行
struct result *pointer = p + k; /* equivalently &p[k] */
pointer->amplitude = data[i];
pointer->position = i;
這將使代碼得以編譯。 請注意,您尚未描述該功能實際上應實現的功能,因此,我不必費心檢查代碼是否確實做了明智的事情。
請注意,您實際上(錯誤地)使用C ++中的C技術。 現代C ++中有更好的替代方法,例如使用標准容器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.