使用指针访问数组中的数据

时间:2011-03-10 17:51:06

标签: c arrays pointers memory-management

我是指针的新手,因此遇到了一些困难。我确实相信,对你来说,解决这个问题应该很容易。问题在于代码。

 // flags is an array of data that I create, manipulate, but now having trouble accessing elsewhere. 
int *flags = (int *) malloc(1* sizeof(int)); // let us start with 1 and then add more within the method. This should continue until we have all the flags we want.  
int number_of_flags = event_extractor(vocal_data, size, flags);

// I want to use flags here, but it doesn't work 

place_effects_on_events(vocal_data, flags, number_of_flags , events_with_effects);

其他方法:

int event_extractor (int *audio_samples, unsigned int size_of_audio, int *flags)
{

int number_of_flags = apply_threshold (lopass_samples, length, &flags);

    // the data prints absolutely correctly here.   
for (int i = 0; i < number_of_flags; i++) {
    printf("FLAG %i  -- %d \n", i, flags[i]);
}
}





 int apply_threshold (int *audio_samples, unsigned int size_of_audio, int **event_flags)
 {


int flag = 0; // this will be the number of flags that I have 
bool run = true; // this will make sure that a minimum amount of time passes before I grab another flag. It's a guard.
int counter = 0; // this is the counter for the above guard. 




int threshold = calculate_threshold_value(audio_samples, size_of_audio);



int length = (int)size_of_audio;




for (int i = 0; i < length-1; i++) 
{

    if (audio_samples[i] > threshold  && run) 
    {


        *event_flags = (int*)realloc(*event_flags, sizeof(int) * (flag + 1));
        (*event_flags)[flag] = i;

        flag++;
        run = false;


    }   

    if (!run) {
        counter++;
        if (counter > 20100) { // hardcode minimum size for now. 
            counter = 0;
            run=true;
        }
    }



}


for (int i = 0; i <10 ; i++) {
    printf("VOCAL SAMPLE %i  %i \n", i-5,audio_samples[*event_flags[1]+i-5] );
}

return flag;

}

问题在这里

 void place_effects_on_events (int *vocal_samples, int *flags, int number_of_flags ,int *events_with_effects)
 {


// here the data does not print correctly 
for (int i = 0; i < number_of_flags; i++) {
    printf("FLAG %i  -- %d\n", i,  flags[i]);
}

2 个答案:

答案 0 :(得分:2)

您应该将指针flags传递给event_extractor

int number_of_flags = event_extractor(vocal_data, size, &flags);

并将其原型更改为

int event_extractor (int *audio_samples, unsigned int size_of_audio, int **flags)

否则,flags本身永远不会更新,仍然指向第一个malloc ed内存区域。由于此时此内存区域不再存在,因此访问其内容将导致未定义的结果。

答案 1 :(得分:0)

您正在将标志传递给event_extractor。尝试传递&amp;标志。我想你想在调用event_extractor函数后更新标志。还有一点:您没有从event_extractor函数返回number_of_flags。