JohnDoe
JohnDoe

Reputation: 915

Adding elements to an array within a for loop

I would like to fill an array by looping through an for loop.

Let's say I have:

int8 myArray[30] = {0};  // Declaring and initializing an array which contains maximum 30 elements  

Adding elements to an array within a for loop:

for (i = 0; i<5; i++)
{
    myArray[0+(i*5)] = getNumberfromFunction1();
    myArray[1+(i*5)] = getNumberfromFunction2();
    myArray[2+(i*5)] = getNumberfromFunction3();
    myArray[3+(i*5)] = getNumberfromFunction4();
    myArray[4+(i*5)] = getNumberfromFunction5();
    myArray[5+(i*5)] = getNumberfromFunction6();
}

Each Element of the loop shall be filled like:

myArray[0] = getNumberfromFunction1();

myArray[1] = getNumberFromFunction2();

...

...

myArray[5] = getNumberFromFunction6();

myArray[6] = getNumberFromFunction1();

....

....

The first turn with i=0 I, the index is correct:

myArray[0] = ..
myArray[1] = ..
..
..
myArray[5] = ..

The problem starts when i = 1:

Than I will have instead of myArray[6], myArray[5].

The first index in the foor loop will be always overwritten by the last index of the foor loop.

Any suggestions how to handle this?

Upvotes: 2

Views: 113

Answers (3)

abhiarora
abhiarora

Reputation: 10430

You are simulating a two-dimensional array on the top of a single dimensional array in C (However, both are laid out contiguously in memory). You can achieve the same thing by having a two-dimensional array like this:

int array[5][6];

for (row = 0; row < 5; row++) {
    for (col = 0; col < 6; col++)
        array[row][col] = myFunc();
}

Or if you want to do it in your way, then you need to update your number from 5 to 6 as you are trying to have an array with 5 rows and 6 columns. See this answer to know how multi-dimensional arrays formatted in memory.

for (i = 0; i < 5; i++) {
    myArray[0+(i*6)] = getNumberfromFunction1();
    myArray[1+(i*6)] = getNumberfromFunction2();
    myArray[2+(i*6)] = getNumberfromFunction3();
    myArray[3+(i*6)] = getNumberfromFunction4();
    myArray[4+(i*6)] = getNumberfromFunction5();
    myArray[5+(i*6)] = getNumberfromFunction6();
}

Upvotes: 1

Adrian Mole
Adrian Mole

Reputation: 51825

In each run of your for loop, your are adding six values to the array! Thus, on each subsequent run, your should increment the "offset" count by i*6 (not i*5, as you have done):

for (i = 0; i<5; i++)
{
    myArray[0+(i*6)] = getNumberfromFunction1();
    myArray[1+(i*6)] = getNumberfromFunction2();
    myArray[2+(i*6)] = getNumberfromFunction3();
    myArray[3+(i*6)] = getNumberfromFunction4();
    myArray[4+(i*6)] = getNumberfromFunction5();
    myArray[5+(i*6)] = getNumberfromFunction6();
}

Try this.

Upvotes: 5

Marce
Marce

Reputation: 477

You could multiply i by 6 instead of 5.

Upvotes: 4

Related Questions