You can find out the size of an array if you can access the original array itself. However, passing an array to a function means that you can't tell how big the array is inside the function. So you have to pass the size of the array to the function.
Also, all but the leftmost array element has to have a size in it.
To get the number of elements in an array, use sizeof(array)/sizeof(*array) (or array[0] instead of *array). Note that this works for arrays with any arbitrary number of dimensions. For example:
Code:
int array[2][3][4];
size_t x = sizeof(array) / sizeof(*array); /* = 2 */
size_t x2 = sizeof(array) / sizeof(array[0]); /* = 2 */
size_t y = sizeof(*array) / sizeof(**array); /* = 3 */
size_t y2 = sizeof(array[0]) / sizeof(array[0][0]); /* = 3 */
size_t z = sizeof(**array) / sizeof(***array); /* = 4 */
size_t z = sizeof(array[0][0]) / sizeof(array[0][0][0]); /* = 4 */
Anyway -- here's food for thought.
Code:
#include <iostream>
void print_array(int array[3][3]);
void print_any_array(int array[], size_t elements);
void print_2D_array(int array[][3], size_t elements);
int main(void) {
int array[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
print_array(array);
print_2D_array(array, sizeof(array) / sizeof(*array));
return 0;
}
void print_array(int array[3][3]) {
for(int x = 0; x < 3; x ++) {
for(int y = 0; y < 3; y ++) {
std::cout << array[x][y] << ' ';
}
std::cout << std::endl;
}
}
void print_any_array(int array[], size_t elements) {
for(size_t i = 0; i < elements; i ++) {
std::cout << array[i] << ' ';
}
}
void print_2D_array(int array[][3], size_t elements) {
for(size_t i = 0; i < elements; i ++) {
print_any_array(array[i], 3);
std::cout << std::endl;
}
}