I have a 2D C-style array from which I have to pass just one column of it to a function. How do I do that?
Basically I need the C/C++ equivalent of the MATLAB command A[:,j]
which would give me a column vector. Is it possible in C/C++?
We can pass the 2D array as an argument to the function in C in two ways; by passing the entire array as an argument, or passing the array as a dynamic pointer to the function.
Example 2: Pass Arrays to Functions To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.
You have 3 options,
1) Pass a pointer to your object (after moving it to the first element of the destination column)
twoDArray[0][column]
Now you can calculate the next item for this column (by jumping through the elements)
2) Create a wrapper class that would do this for you.
custom2DArray->getCol(1);
.
.
.
class YourWrapper{
private:
auto array = new int[10][10];
public:
vector<int> getCol(int col);
}
YourWrapper:: vector<int> getCol(int col){
//iterate your 2d array(like in option 1) and insert values
//in the vector and return
}
3) Use a 1d array instead. You can get this info easily. By jumping through rows and accessing the value for the desired column.(Mentioning just for the sake of mentioning, don't hold it against me)
int colsum(int *a, int rows, int col)
{
int i;
int sum = 0;
for (i = 0; i < rows; i++)
{
sum += *(a + i*rows+col);
}
return sum;
}
int _tmain(int argc, _TCHAR* argv[])
{
int rows = 2;
int cols = 2;
int i, j;
int *a;
a = (int*)malloc(rows*cols*sizeof(int));
// This just fills each element of the array with it's column number.
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
*(a+i*rows + j) = j;
}
}
// Returns the sum of all elements in column 1 (second from left)
int q = colsum(a, rows, 1);
printf("%i\n", q);
return 0;
}
It's not exactly passing the column, it's passing a pointer to the beginning of the array and then giving it instructions on how many rows the array has and which column to concern itself with.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With