二维指针输出矩阵

时间:2018-09-29 02:28:11

标签: c++

我想创建一个非矩形矩阵,可以输出如下内容:

0 0 0 0 0 0
0 0 0
0 0 0 0 
0 0 0 0 0 0

使用二维指针。

我有一个1D指针,该指针指向一个数组,该数组存储每一行​​的大小:{6、3、4、6,-1}。

-1是一个将停止while循环的标志。

#include <iostream>
using namespace std;


template<class T>
T** allocate(int* sizes) {

    T** twod; // 2-dimensional pointer

    while (*sizes != -1) { // the loop will stop when *sizes hit -1
        *twod = new T[*sizes];
        twod++;
    }

    return twod;
}

int main() {
    int array[] = {6,3, 4, 6, -1};
    int* sizes = array; // 1-D pointer to the array which stores the size of each row

    int** twod = allocate<int>(sizes);

    for(int i = 0; i < 5; i++){
        for(int j = 0; j < *(sizes+i); j++){
            twod[i][j] = 0;
            cout << twod[i][j] << " ";
        }
        cout << endl;
    }
}

程序不输出任何内容。你们能帮我在这里指出问题吗?我认为这可能与while循环有关。

非常感谢!

(这是我关于指针使用的一项工作。我必须使用指针来输出上面的内容。我知道使用静态数组要容易得多)

1 个答案:

答案 0 :(得分:1)

输出不符合您的期望,仅仅是因为您的allocate()函数不合逻辑。 您可以尝试:

#include <iostream>
using namespace std;

template<class T>
T** allocate(int* sizes) 
{

   T** twod; // 2-dimensional pointer
   for(int i = 0;(*sizes)!=-1;i++)
   {
      twod[i] = new T[*sizes];
      sizes++;
   }
   return twod;
}