noddy
noddy

Reputation: 1010

passing a column out of a matrix to a function in c

I want to pass a particular column of the matrix that I have in my program to a function. If I use the call <function_name>(<matrix_name>[][<index>]); as the call then I get the error

error: expected expression before ‘]’ token

So please help me in finding the suitable way Thanks

Upvotes: 3

Views: 4444

Answers (4)

Sogger
Sogger

Reputation: 16122

Because of the way addressing works, you can't simply pass the 'column' since, the 'column' values are actually stored in your 'rows'. This is why your compiler will not allow you to pass no value in your 'row' reference, ie: '[]'.

An easy solution would be to pass the entire matrix, and pass the column index as a seperate integer, and the number of rows. Your function can then iterate through every row to access all members of that column. ie:

functionName(matrixType** matrixRef, int colIndex, int numRows)  
{  
   for(int i=0; i< numRows; ++i)  
      matrixType value = matrixRef[i][colIndex]; //Do something  
}

Upvotes: 2

Tony Arkles
Tony Arkles

Reputation: 1946

There's a few things you need to keep in mind about C here.

I'm assuming your matrix is stored as a 2D array, like this:

float mat[4][4];

What you need to remember is that this is just 16 floats stored in memory consecutively; the fact that you can access mat[3][2] is just a shortcut that the compiler gives you. Unfortunately, it doesn't actually pass any of that metadata on to other function calls. Accessing mat[3][2] is actually a shortcut for:

mat[ (3*4 + 2) ]

When you pass this into a function, you need to specify the bounds of the matrix you're passing in, and then the column number:

void do_processing(float* mat, int columns, int rows, int column_idx)

Inside this function, you'll have to calculate the specific entries yourself, using the formula:

mat[ (column_idx * rows) + row_idx ]

Upvotes: 1

Gavin H
Gavin H

Reputation: 10482

You are going to have to reformat the data. The column is not contiguous in memory. If for example you have an array:

arr[5][4]

Then trying to pass a 'column' would be like trying to pass every 5th element in the array. Think of it as one giant array.

Upvotes: 1

peoro
peoro

Reputation: 26060

The syntax you used doesn't exist.

Matrices are stored in memory by row (or better, by the second dimension, to which you give the semantics of rows), so you cannot natively. You could copy all your column elements in a vector (a single dimension array) and pass it.

If you need to work only by column (and never by row) you could change the semantics you give to the first and to the second dimension: think of your matrix as matrix[row][column] instead of matrix[column][row].

Otherwise, if you need to do this often, look for a better data structure, instead of a simple array.

Upvotes: 5

Related Questions