carraysnesc

Populating an array from a large array, two elements at a time


I have an array of 10 random elements, generated like this:

             for ( j = 0;j<10;j++)
                {

                    file[j] = rand();

                    printf("Element[%d] = %d\n", j, file[j] );                  
                }

Then I generate a new array with 2 elements. The value of the array is taken from the array above, and placed into the array with 2 elements. Like in the code sample below:

         for(i = packet_count, j = 0; j < 2; ++j, ++i)
            {
                    packet[j] = file[i] ;
                    ++packet_count ;
                    printf("\npacket: %d", packet[j]);

            }
                printf("\nTransmit the packet: %d Bytes", sizeof(packet));

The output is shown below:

Telosb mote Timer start.
Element[0] = 36
Element[1] = 141
Element[2] = 66
Element[3] = 83
Element[4] = 144
Element[5] = 137
Element[6] = 142
Element[7] = 175
Element[8] = 188
Element[9] = 69

packet: 36
packet: 141
Transmit the packet: 2 Bytes

I want to run through the array and take the next two values and place them in the packet array and so on, until the last element in the array.


Solution

  • You can run through the big array, and select the values to be copied in the little array, resseting j to zero when it is equal to 2:

    j = 0;
    for(i = 0; i < 10; i++) {
      packet[j] = file[i];
      printf("\npacket: %d", packet[j]);
      j++;
      if(j == 2) { 
        j = 0;
        printf("\nTransmit the packet: %d Bytes", sizeof(packet));
      }
    }