2 Replies - 150 Views - Last Post: 17 March 2012 - 11:14 AM Rate Topic: -----

#1 erkant  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 108
  • Joined: 26-October 10

Partitioning an array?

Posted 17 March 2012 - 10:50 AM

I have a question regarding arrays.

Let's say that I have an array with 144 elements, let's say that it is test[144], and all of the elements has their own values. Simply, all the array elements are assigned to certain values. Now I need to group them (partition them, or say create blocks) with 48 elements and send them to a certain function, what I mean is that I need the first 48 elements of the array called test, then second 48 elements, and finally the last 48 elements.

So how can I do this in C? And what if the user enters the size of the array and I need to group (partition) the elements as explained above?

Thanks in advance.

This post has been edited by erkant: 17 March 2012 - 10:52 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Partitioning an array?

#2 r.stiltskin  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1833
  • View blog
  • Posts: 4,927
  • Joined: 27-December 05

Re: Partitioning an array?

Posted 17 March 2012 - 10:57 AM

Unlike some other languages (for example, Fortran and Python) C and C++ don't have built-in array slicing facilities. But it's still very easy to send "pieces" of an array to a function. Remember that in C and C++ an array isn't an "object" in the OOP sense. It's just a contiguous region of memory. When you send an array to a function, you're actually just sending a pointer -- the address of the beginning of the array. The function has no way of knowing the size of the array unless you send the size as an additional parameter.

So this makes the answer to your question very easy -- you don't have to do this any differently than you would do if the array size was exactly 64. Let's say that you declared the array as
int big_array[256];
so big_array (which is the same as &big_array[0]) is actually the starting address of this array.
On the first function call you provide the starting address big_array and the size (64). On the next call, you want to provide the address of big_array[64], which is big_array + 64, and the size (64). And so on...
const char size = 64;
int big_array[size];
// initialize the array 
// ...

// function calls
fun( big_array, size );
fun( big_array+size, size );
fun( big_array+2*size, size );
// ...


Was This Post Helpful? 2
  • +
  • -

#3 erkant  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 108
  • Joined: 26-October 10

Re: Partitioning an array?

Posted 17 March 2012 - 11:14 AM

Thanks for the information r.stiltskin. It was much useful. If I have any questions or problems regarding it, I will reply. But it seems easy.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1