我想设计一个函数,该函数初始化一个数组并返回指向该数组的指针。使用动态内存分配,我想使用相同的函数来初始化1维数组,将指针返回数组(* p),还用于初始化2维数组,返回双指针(** p)。
我尝试使用模板来完成此任务,但出现此错误
C:/Users/USER/Documents/code_lite/005/main.cpp:61:2: warning: 'auto' changes meaning in C++11; please remove it [-Wc++0x-compat]
auto **mat1 = initializare<double**, double>(2, 3, 3);
^
C:/Users/USER/Documents/code_lite/005/main.cpp:61:54: error: cannot convert 'double**' to 'int**' in initialization
auto **mat1 = initializare<double**, double>(2, 3, 3);
^
C:/Users/USER/Documents/code_lite/005/main.cpp:61:9: warning: unused variable 'mat1' [-Wunused-variable]
auto **mat1 = initializare<double**, double>(2, 3, 3);
^
mingw32-make.exe[1]: *** [Debug/main.cpp.o] Error 1
#include <iostream>
#include <stdlib.h>
#include <cstdarg>
using namespace std;
template<typename T, typename U>
T initializare(int num,...)
{
va_list list;
va_start(list, num);
switch(num)
{
case 1:
{
// code for array of 1 dimension
return mat;
}
case 2: //code for array of 2 dimension
{
int val=va_arg(list,int);
T mat = new U *[val];
T begin = mat;
T endm = mat + val -1;
for(int i=2; i < num; i++)
{
val=va_arg(list,int);
mat[i] = new U[val];
if (mat[i] == NULL)
exit(1);
}
std::cout << "read array \n";
for(;begin <= endm; begin++)
{
U *bgn =*begin;
U *end =*begin + val - 1;
for(;bgn <= end; bgn++)
std::cin >> *bgn;
}
return mat;
}
default: // cod for array which has dimension grater than 2
}
}
int main()
{
int l1, c1, c2, l2;
std::cin >> l1 >> c1 >> c2 >> l2;
auto **mat1 = initializare<double**, double>(2, 3, 3);
// initializare<type, type>(dimension of array = 2 , number of lines =
// 3, number of columns =3 )
return 0;
}