Answer the question
In order to leave comments, you need to log in
Is it possible to make a function that takes any two-dimensional array to calculate the sum of its elements?
In this case, the function takes a pointer to an array of two elements. Is it possible to make the function accept an array of any size? We pass any array, pass the number of rows and columns, and calculate the sum. And it turns out that the function is now sharpened for an array of a specific size, more precisely, for an array that contains arrays of a constant value, always only 2.
#include <stdio.h>
#include <conio.h>
#define ROWS 3
#define COLS 2
int sum(const int(*arr)[COLS], int rows, int cols);
int main(void)
{
const int arr[ROWS][COLS] = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
printf("%d", sum(arr, ROWS, COLS));
_getch();
return 0;
}
int sum(const int (*arr)[COLS], int rows, int cols)
{
int total = 0;
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
total += *(*(arr + i) + j);
return total;
}
Answer the question
In order to leave comments, you need to log in
(takes a tin bullhorn) Aw, this is C++
There is a std::vector and Eigen in general
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question