1

What is the best way to split an array(mainArr) that holds 50 random integers into 5 different arrays that all contain 10 of the integers in each?

For example arr1 holds mainArr's 0-9 values, arr2 holds 10-19....

I have searched around but everything is splitting the array into two different arrays. Any help would be appreciated. Thanks.

7
  • 4
    Can you do something like int *arr1 = mainArr, *arr2 = mainArr + 10, ... Commented Nov 12, 2015 at 22:30
  • 1
    2 is multiple. Can't you apply the solution for "1 array to 2 arrays" to "1 array to N arrays"? Commented Nov 12, 2015 at 22:31
  • 1
    Exploit the fact is in C/C++, arrays act like pointers. Simply create 5 pointers, which point to the 0th, 10th, 20th, 30th and 40th cells in the array Commented Nov 12, 2015 at 22:39
  • It's not like Java or Python, in which array is kind of object that is defined with length that you can always query. In C/C++, you as a programmer are responsible to always know your array size. Just treat your 50-sized array as 5 10-sized arrays Commented Nov 12, 2015 at 22:41
  • @SomethingSomething but the 0th array contains all elements of mainArr? Commented Nov 12, 2015 at 22:41

2 Answers 2

3

To be a little more generic:

int mainArr[50];
int *arr[5];

int i;
for(i = 0; i < 5; i++)
    arr[i] = &mainArr[i*10];

And then access for example mainArr[10] as arr[1][0].

Sign up to request clarification or add additional context in comments.

4 Comments

I would change &mainArr[i*10] to mainArr + (i * 10), but it's only my opinion..
@Jason What do you mean? mainArr has only 1 dimension. arr[i] accesses the ith array
This helped alot, I am new to c++ so you will have to forgive me
@Kevin Sorry, you're right. The second array is ragged, not two dimensional.
0

Just define a function that maps each index, 0..49, into another index 0..4. The obvious function is division by 10. Modulus by 5 also works though.

int a[50];
int b[5][10];

for (size_t i = 0; i < 50; i++)
  b[i/10][i%10] = a[i];

or

int a[50];
int b[5][10];

for (size_t i = 0; i < 50; i++)
  b[i%5][i/5] = a[i];

See @nnn's solution for an example that re-uses the same memory.

Comments

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.