3

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.

  • 3
    You should have a look at [How to pass 2D array (matrix) in a function in C?](https://stackoverflow.com/q/3911400/5291015) and [How to pass a multidimensional array to a function in C and C++](https://stackoverflow.com/q/2828648/5291015) – Inian Oct 25 '19 at 04:21
  • 1
    Also, what errors? – Tanveer Badar Oct 25 '19 at 04:41
  • error: array type has incomplete element type ‘float[]’ void displayData (int, int, float[][]); and this error repeats for all of the functions – Noah Howren Oct 25 '19 at 05:01

1 Answers1

4

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.

abhiarora
  • 9,743
  • 5
  • 32
  • 57
  • But the thing is, the size of each dimmension of the array is variable on the user input. – Noah Howren Oct 25 '19 at 05:12
  • @NoahHowren If you don't know the amount of memory you'll need until runtime, you can't use a fixed-sized array. You have to dynamically allocate it or use a VLA. See the first answer to the question posted by Inian in the comments. – yano Oct 25 '19 at 05:18