[英]Issue in Dynamic Memory Allocation
我正在編寫 function 以在給定范圍內的數組中找到峰值。 我不知道給定數組中峰值的確切數量。 所以我使用動態 memory 分配來存儲峰值。 我面臨的問題是,
int *findPeak(float *pArray, int length, int window, int *pCount) {
int i, j ,count = 0, toPositive = 0, toNegative = 0;
float peak;
int *pPeakBuffer;
bool firstZeroCross = false, toPositivePeak = false;
int *peakBuffer = (int*)malloc(1*sizeof(int));
for (i = 0; i < length; i += window) {
if (count == 0) {
peak = 0.0;
for (j = i; j < window; j++) {
if (peak < pArray[j]) {
peak = pArray[j];
peakBuffer[count] = j;
}
}
printf("Peak = %d\n\r", peakBuffer[count]);
count++;
}
else {
peak = 0.0;
peakBuffer = (int*)realloc(peakBuffer, 1*sizeof(int));
for (j = i; j < i+window; j++) {
if (peak < pArray[j]) {
peak = pArray[j];
peakBuffer[count] = j;
}
}
printf("Peak = %d\n\r", peakBuffer[count]);
count++;
}
}
*pCount = count;
printf("count = %d\n\r", count);
for (i = 0; i < count; i++)
printf("%d ,", peakBuffer[i]);
printf("\n\r");
return peakBuffer;
}
當檢測到峰值並將其存儲在第一個 memory 中。 當檢測到第 2 個峰值時,它存儲在第 2 個 memory 中,然后將第一個存儲器(前一個存儲器)中的值更改為零或其他數字,依此類推。 僅獲得第一個和最后一個峰值。 memory 的 rest 存儲了一些未知值(不是峰值)。 我不知道為什么會這樣。
除了 memory 分配問題、邊界問題和“\n\r”誤解之外,您所做的嘗試值得做出可能有用的回應。
剖析 OP 中的代碼並討論不完全正確的地方需要一整天的時間。 對不起。
下面的代碼改編自您的代碼,對問題進行了整理並強制執行似乎是您追求的目標。 您的代碼似乎會嘗試存儲在任何 window 中找到的連續遞增值的索引......真的嗎? 那將是很多索引!
此 function 搜索任何 window 中的單個最大值,並且僅“記錄”這些最大值的索引(在整個數組中,而不僅僅是一個“窗口”),每個 Z05B8C74CBD96FBF2DE4ZC1A3524 一個最大值。
也許這將為您提供實現目標的功能基礎。 (我已經編譯了這個,但沒有用任何數據對其進行測試。“按原樣”提供......
int *findPeak( float *pArray, int length, int window, int *pCount ) {
int i, count = 0;
int *pPeaks = NULL; // ALWAYS initiase pointers
for( i = 0; i < length; i += window ) {
int peak = i; // assume peak is the first one in this window
// scan window finding highest peak
// Notice that 'j' starts with index of beginning of window
// Notice limit to not run beyond length
for( int j = i; j < i + window && j < length; j++ )
if( pArray[ j ] > pArray[ peak ] ) // compare two floats values
peak = j; // remember higher peak
// get room to store this array index
int *tmp = (int*)realloc( pPeaks, (count + 1) * sizeof *tmp );
if( tmp == NULL ) {
/* deal with failure */
exit( EXIT_FAILURE );
}
pPeaks = tmp; // did not fail
pPeaks[ count++ ] = peak; // index relative to entire array
}
// Pointless because this version will find one peak in each window
// Could be calculated by dividing length by window
*pCount = count;
printf( "count = %d\n", *pCount );
for( i = 0; i < count; i++ )
printf( "%d, ", pPeaks[ i ] );
putchar( '\n' );
return pPeaks;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.