Copying every nth element from one array to another

603 Views Asked by At

Does anyone know of a way to copy every nth element from one array to another? For example, I have an array Data[x] and want to copy every third (3rd) element - Data[0], Data[3], Data[6] etc into a new array Data2[j]. I tried using a for loop but with no success.

void StoreData()
{
bufferPointer1 = &BufferA[0];
x=0;
i=0;
j=0;

while (x<NO_SAMPLES-1)
{
    Data[x] = *bufferPointer1;
    bufferPointer1++;
    x++;
    for (j=0; j<127; i++)
        {
        Data2[j] = Data[i+=3];
        j++;
        }
}
}
1

There are 1 best solutions below

0
Grossu Iulian On

Why aren't you declaring the variables in the function? All four of them seem to be used locally and should not be visible outside the function.

Why increment i in this section instead of j, Is this a typo?

   for (j=0; j<127; i++)
        {
        Data2[j] = Data[i+=3];
        j++;
        }

I would write it like this:

   for (j=0; j<127; j++)
        {
        Data2[j] = Data[i];
        i+=3;
        }
    i=0;                      // Reset pointer