2

So, i'm writing some code in C for a larger program processing data for an ECG device. The program has several global int arrays to store data, as it has to continuously filter data, while also using both previous raw and filtered data. Therefore, i have to shift the ints in my arrays once in a while, in order to discard data that will no longer be used to filter and replace it with new raw data and so on. Implementing this is not more difficult than implementing some for loops here and there in my code that do this for me. I would however like to define a function that did this for me, as I do this quite a few times. Therefore I coded such a function, that looked like this:

void updateArray(int array[], int size){
size = size / sizeof(int);
int i;
for(i = size; i > 0; i--){
    array[i] = array[i-1];
}}

But, as I'm not that used to code in C, i have clearly done something wrong here, as using this function yielded wrong data. Debugging the function, I found that when this function is called, the array is shifted as expected, but one of my other arrays has one of its values changed. I'm not really sure why this is, but I really hope some feedback could help me understand the problem better.

1 Answer 1

3

array[size] is beyond the end of your array. You are copying one too many values.

It should be:

void updateArray(int array[], int size) {
    size = size / sizeof(int);
    int i;
    for(i = size - 1; i > 0; i--) {
        array[i] = array[i-1];
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

There's also the question of whether the size value passed in is right ... the code expects it to be the size of array in bytes, but perhaps it isn't. (Though, reading the OP's symptom more carefully, that's probably not the problem.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.