简体   繁体   中英

C language, grouping elements in an array

My code is far too long, complicated and tedious for me to post it here, but suppose you had something like this:

    #include <stdio.h>

char myArray[3000]={3,1,3,1,2,5,1,1,7,0,1,3,0,1,2,0,1,6,0,1,8,9,1,0,0,1,4,3,1,7};

Suppose I wanted to make a new array that takes the two consecutive digits from the above list of elements.

indexes 2-6 of myArray contain (3,1,2,5), how can I get my new array to group elements and store elements 2-6 as (31, 25).

I'm new to programming and I haven't found an efficient way of doing this.

Simplest way to think about it:

int newArray[2];
newArray[0] = myArray[2]*10 + myArray[3];
newArray[1] = myArray[4]*10 + myArray[5];

If you wanted something more generic...

#define NEW_ARRAY_SIZE 5
int newArray[NEW_ARRAY_SIZE];
int offset = 2;
int i = 0;
for ( i = 0; i < NEW_ARRAY_SIZE; ++i )
{
   newArray[i] = myArray[offset+2*i]*10 + myArray[offset+2*i+1];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM