There is a task, a two-dimensional dynamic array is given, to calculate the sum in columns, well, the compiler swears at this place sum = sum + arr[j]; Writing a value of type "int *" can not be assigned to an entity of type "int" Please, tell me how to write correctly. Directly the code itself:

 #include "stdafx.h" #include <iostream> #include <ctime> using namespace std; int main() { srand(time(0)); int N; int M; int sum; cout << "Vvedite N - kolvo strock" << endl; cin >> N; cout << "Vvedite M - kolvo stolb" << endl; cin >> M; int **arr = new int*[N]; for (int i = 0; i < N; i++) arr[i] = new int[M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { arr[i][j] = 1 + rand() % 100; cout << arr[i][j]<<"\t"; sum = sum + arr[j]; } cout << endl; cout << sum << "\n"; } for (int i = 0; i < N; i++) delete[] arr[i]; delete[] arr; system("pause"); return 0; } 

    2 answers 2

    You have a two-dimensional array, to get the value of an array, you must use indexing for each dimension, so

     sum = sum + arr[i][j]; 

    In your case, you get a pointer to an array, that is, int*

      You assign an int to a variable of type int.

       sum = sum + arr[j]; 

      use

       sum = sum + arr[i][j]; 
      • @tillin This is what he considers the sum of the entire array, right? - Mr.Flatman
      • @ Mr.Flatman Yes, the whole array. The question was about a compilation error, did I understand correctly? - tilin
      • @tillin Yes, the question was about compiler errors, now I'll go figure out how to implement the calculation of the sum of columns. - Mr.Flatman