By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,661 Members | 779 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,661 IT Pros & Developers. It's quick & easy.

How to pass sub-portion of an array to a function

P: n/a
Hi

I'm looking for an efficient way to pass a sub-portion of an 2D array to a function, which takes that sub-portion and does some calculation with it, but the values do not get changed inside the function.

So if I have 10 by 10 2D array K

K[10][10]

I want to pass, say 1st row to 3rd row of 2nd and 3rd column to a function

fun( <subset of K>, rowDim, colDim )

The function definition should be..(?)

void fun(???, int row, int col){

}

Now I can define a 2 by 3 array and copy the values of K into it, and pass that into function, but I'm sure there's better way to do it.

I'd appreciate your expert help!

Mao
Oct 29 '10 #1
Share this Question
Share on Google+
1 Reply


P: 14
In C/C++, what you described is a 3 by 2 array, not 2 by 3.

Assuming you are writing the function (not trying to use a pre-existing library function), you can pass the address of the beginning of the subarray, the dimensions of the subarray, and the offset (i.e. the size of the second dimension/number of columns) of the original array. Your function can use that offset to navigate through the subarray.

So the function signature would be
void fun( type *begin, int rows, int cols, int offset, [other params?] )

Using your example, when calling the function you would use:
fun( K+1, 3, 2, 10, [other params?] );

Inside the function each element can be located by dereferencing (begin + row * offset + subcol) where subcol means the column in the subarray. So the value of the element in the 2nd row, 2nd column of the subarray is:
*(begin + 1 * 10 + 1)

(Remember that in C/C++ arrays begin at [0,0] so the 2nd row, 2nd column is row 1, col 1.)
Oct 29 '10 #2

Post your reply

Sign in to post your reply or Sign up for a free account.