Reputation: 85
I have to pass a float value 2 dimensional array into a couple functions, and I cannot figure it out for the life of me. This is where I declare them and where I get my errors when compiling.
void displayData (int, int, float[][]);
void hasValue (int, int, float[][]);
void countValues(int, int, float[][]);
Every time I compile I get errors and I just want to finish this assignment before I lose it.
Upvotes: 3
Views: 1637
Reputation: 10430
C
programming language does not really have Multi-Dimensional Arrays
, but there are several ways to simulate them. The way to pass such arrays to a function depends on the way used to simulate the multiple dimensions. I think you want to use Dynamically Allocated VLA
. See this link for more info.
In C
(& C++
), the data of your 2D Array will be stored row-by-row
(Row-Major Order
) and the length of a row is always necessary to get to the proper memory offset for the next row. The first subscript therefore only indicates the amount of storage that is needed when the array is declared, but is no longer necessary to calculate the offset afterwards. So, you can leave first subscript empty and you need to provide the rest of subscripts in the function declaration and definition.
For example, if your array column size is 4, then:
void displayData (int, int, float[][4]);
void hasValue (int, int, float[][4]);
void countValues(int, int, float[][4]);
EDIT:
You can use the function below to achieve what you want:
void my_function(int rows, int cols, int array[rows][cols])
{
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
array[i][j] = i*j;
}
}
}
You need to make sure you pass the array of right size to your function.
Upvotes: 4