Мисля, че не може да върне самия масив, а само указател към него:
- Код: Избери целия код
#include <iostream>
using namespace std;
int** Sum(int a[][2], int b[][2])
{
int** c = new int*[3];
for(int i = 0; i < 3; i++)
{
c[i] = new int[2];
for(int j = 0; j < 2; j++)
c[i][j] = a[i][j] + b[i][j];
}
return c;
}
int main()
{
int a[3][2] = {{1, 2}, {3, 4}, {5, 6}},
b[3][2] = {{7, 8}, {9, 10}, {11, 12}};
int** c = new int*[3];
for(int i = 0; i < 3; i++)
c[i] = new int[2];
c = Sum(a, b);
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 2; j++)
cout << c[i][j] << "\t";
cout << endl;
}
cout << endl;
for(int i = 0; i < 3; i++)
delete[] c[i];
delete c;
return 0;
}
Само, че при това положение не виждам как ще изтрием указателя съм 'с' в Sum. Не можем да го направим преди return, защото ще го изгубим, и няма да върнем нищо. Сигурно е по-добре да не заделяме памет за 'c' в main(). Така в main() ще използваме указател, върнат от Sum, към резултатния масив, изчислен в Sum:
- Код: Избери целия код
#include <iostream>
using namespace std;
int** Sum(int a[][2], int b[][2])
{
int** c = new int*[3];
for(int i = 0; i < 3; i++)
{
c[i] = new int[2];
for(int j = 0; j < 2; j++)
c[i][j] = a[i][j] + b[i][j];
}
return c;
}
int main()
{
int a[3][2] = {{1, 2}, {3, 4}, {5, 6}},
b[3][2] = {{7, 8}, {9, 10}, {11, 12}};
int** c = Sum(a, b);
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 2; j++)
cout << c[i][j] << "\t";
cout << endl;
}
cout << endl;
for(int i = 0; i < 3; i++)
delete[] c[i];
delete c;
return 0;
}
А с шаблон е още по-добре (така размерите на масивите се предават автоматично):
- Код: Избери целия код
#include <iostream>
using namespace std;
template <int m, int n> int** Sum(int (&a)[m][n], int (&b)[m][n])
{
int** c = new int*[m];
for(int i = 0; i < m; i++)
{
c[i] = new int[n];
for(int j = 0; j < n; j++)
c[i][j] = a[i][j] + b[i][j];
}
return c;
}
int main()
{
int a[4][2] = {{1, 2}, {3, 4}, {5, 6}, {7, 8}},
b[4][2] = {{9, 10}, {11, 12}, {13, 14}, {15, 16}};
int** c = Sum(a, b);
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 2; j++)
cout << c[i][j] << "\t";
cout << endl;
}
cout << endl;
for(int i = 0; i < 4; i++)
delete[] c[i];
delete c;
return 0;
}