user39086
user39086

Reputation: 165

In C and C++, how to move some elements in an array into a new array?

For example, how can I move the 1st, 5th and 10th elements in array A to a new three-elements array B without assigning separately for three times?

Upvotes: 0

Views: 105

Answers (2)

ouah
ouah

Reputation: 145839

In C, just declare and initialize a new array with the selected elements of your array. No assignment needed.

int main(void)
{
    int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int b[3] = {a[0], a[4], a[9]};

    return 0;
}

Remember that initializers for arrays with automatic storage duration does not have to be constants.

Upvotes: 3

ikh
ikh

Reputation: 10417

Just do the three assignments! Why do you avoid it?

int ar1[10], ar2[10];

ar2[0] = ar1[0];
ar2[4] = ar1[4];
ar2[9] = ar1[9];

However, if you have lots of indices to move, perhaps you need another way.

I suggest this:

int ar1[1000], ar2[1000];

int indices[] = { 1, 3, 54, 6, 23, 35, 9, 42, 44, 995, 722, .... };
for (int i = 0; i < sizeof(indices) / sizeof(indices[0]); i++)
{
    ar2[i] = ar1[i];
}

Upvotes: 0

Related Questions