Reputation: 495
Directions given: Write a function int getLength(int grid[][6]) that computes the number of elements contained within the 2-D array.
My first question is: How do we pass an array into a function? I get an error when I try to do that.
int x[][2] = {{ 1, 2 }, { 2, 3 }};
int getLength(x);
Error: a value of type "int (*)[2]" cannot be used to initialize an entity of type "int"
============================================================
Also, is this as simple as just using sizeof() like so?:
int getLength(int grid[][6]){
cout << sizeof(grid);
return sizeof(grid);
}
Upvotes: 0
Views: 209
Reputation: 6407
If you task is to send 2D-array of any size to function just sent pointer and two sizes. But if you want to measure size by such function, be careful sizeof(grid);
will calculate a size of pointer 4 or 8 (i.e. 32 or 64 bit depending on your system) but not size of array.
Upvotes: 0
Reputation: 193
#include <iostream>
using namespace std;
int getLength(int x[][2]);
void main(){
int x[][2] = { { 1, 2 }, { 2, 3 } };
int y = getLength(x);
cout << y << endl;
}
int getLength(int x[][2]){
cout << sizeof(x) << endl;
for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++)
cout << x[i][j]<<" ";
cout << endl;
}
return sizeof(x);
}
This result is
4
1 2
2 3
4
Isn't it your interest?
Upvotes: 0
Reputation: 254751
That's impossible. When an array is passed to a function, it decays to a pointer, leaving no way to retrieve the array size.
You could use a template to extract the size from the array type:
template <size_t N, size_t M>
size_t getLength(int (&)[N][M]) {return N*M;}
By passing the array by reference, it retains its type, from which the template arguments can be deduced automatically to give the return value.
Upvotes: 2
Reputation: 12688
If you're passing a 2-D array to function getLength()
as
int x[][2];
getLength(x);
the function declaration should be:
getLength(int x[][2]) { .. }
In the above declaration number of rows need not be specified as we are not allocating the memory for the array hence can be ignored. Number of columns is required for the dimension of the array.
The size of 2D array can be calculated as:
ROW * COL * sizeof x[0][0]
Upvotes: 1