This week's book giveaway is in the Design forum.We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!

# C Integer Array Extraction

Greenhorn
Posts: 20
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 extracting some elements of array "a[5]" 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 it be possible using C programming?

Henry Wong
author
Marshal
Posts: 20995
76
• 1
sashwat kumar padhy wrote: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 extracting some elements of array "a[5]" 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 it be possible using C programming?

Depends on what you mean by extraction. If you mean two new arrays, which contains a copy of the elements of the original array, then allocate the two new arrays, use a loop, and copy the elements.

However -- and this is one of the cool things about C and pointer arithmetic -- if you mean for the two new arrays to be backed by the original array, then you can do it with pointers. In C, a pointer behaves just like an array (or more correctly, an array behaves like a pointer). So, the "b" array is just an int pointer, pointing to the zeroth element of the "a" array. And the "c" array is just an int pointer, pointing to the second element of the "a" array.

Henry

Greenhorn
Posts: 20
Henry Wong wrote:
sashwat kumar padhy wrote: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 extracting some elements of array "a[5]" 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 it be possible using C programming?

Depends on what you mean by extraction. If you mean two new arrays, which contains a copy of the elements of the original array, then allocate the two new arrays, use a loop, and copy the elements.

However -- and this is one of the cool things about C and pointer arithmetic -- if you mean for the two new arrays to be backed by the original array, then you can do it with pointers. In C, a pointer behaves just like an array (or more correctly, an array behaves like a pointer). So, the "b" array is just an int pointer, pointing to the zeroth element of the "a" array. And the "c" array is just an int pointer, pointing to the second element of the "a" array.

Henry

Thank you..I wanted to make separate arrays which are independent of the array "a".Did it using memcpy.