[英]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.