1

I have an array of integers. Let's assume

int a[5]={1,2,1,2,2};

I want to divide this array into two arrays by copying some elements of array a into some different arrays like b[2] and c[3], such that int b[2] will contain {1,2} and int c[3] will contain {1,2,2}.

How can this be achieved using C?

4
  • 2
    You mean copy them into new arrays or just define new ways of referencing the parts of the original arrays? Commented Aug 13, 2013 at 17:27
  • 1
    What did you try? Where did you run into difficulty? Commented Aug 13, 2013 at 17:34
  • 1
    Do you understand how to access the elements of an array? Do you understand how to assign to an element of an array? Why wouldn't just do the naive approach of looping and assigning elements of the destination arrays from the values of the source array? The memcpy approach described above is more efficient, but you don't give any impression that you even understand how to do it in a straight forward way. I'm tempted to downvote the question, but I really can't tell if you're being lazy or you really don't know anything about programming. Commented Aug 13, 2013 at 17:39
  • I got the solution by using memcpy..I was unaware of memcpy. Thanks for the help. Commented Aug 14, 2013 at 16:44

3 Answers 3

6

You can copy the data into new arrays using memcpy:

int b[2], c[3];
memcpy(b, a, sizeof(b));
memcpy(c, &a[2], sizeof(c));

However, if you do not need the results to be two independent arrays, and would not mind them being pointers, you can do this:

int *b= a, *c = &a[2];

These two pointers can be used in ways similar to arrays except for two important differences:

  • sizeof(b) and sizeof(c) will represent the size of the pointer, not of the array
  • The memory pointed to by the two pointers would not be independent of the original a[5] array.

If you print the content of memory pointed to by these two pointers, you would get the same results as if they were arrays:

for (int i =0 ; i != 2 ; i++) {
    printf("b[%d]=%d\n", i, b[i]);
}
for (int i =0 ; i != 3 ; i++) {
    printf("c[%d]=%d\n", i, c[i]);
}
Sign up to request clarification or add additional context in comments.

2 Comments

+1 for great answer (posted it about 10 seconds before I did). memcpy is much less code than looping (or any other alternative).
I got the solution by using memcpy..I was unaware of memcpy. Thanks for the help.
2
int a[5] = {1,2,1,2,2};
int b[2], c[3];

memcpy(b, a, sizeof(b));
memcpy(c, a + 2, sizeof(c));

1 Comment

I got the solution by using memcpy..I was unaware of memcpy. Thanks for the help.
1

If you just want to reference the specified element of the original array:

int *b = a + 3; //  b[0] = a[3]

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.