D
D
dandropov952018-08-23 23:26:39
C++ / C#
dandropov95, 2018-08-23 23:26:39

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

2 answer(s)
A
Armenian Radio, 2018-08-23
@gbg

(takes a tin bullhorn) Aw, this is C++
There is a std::vector and Eigen in general

J
jcmvbkbc, 2018-08-24
@jcmvbkbc

How to put an n-dimensional array into a function argument?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question