亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從函數返回一個二維數組

從函數返回一個二維數組

C++
HUWWW 2019-08-28 09:34:33
從函數返回一個二維數組嗨,我是C ++的新手,我試圖從一個函數返回一個二維數組。就是這樣的int **MakeGridOfCounts(int Grid[][6]){   int cGrid[6][6] = {{0, }, {0, }, {0, }, {0, }, {0, }, {0, }};   return cGrid;}
查看完整描述

3 回答

?
神不在的星期二

TA貢獻1963條經驗 獲得超6個贊

此代碼返回2d數組。

 #include <cstdio>

    // Returns a pointer to a newly created 2d array the array2D has size [height x width]

    int** create2DArray(unsigned height, unsigned width)
    {
      int** array2D = 0;
      array2D = new int*[height];

      for (int h = 0; h < height; h++)
      {
            array2D[h] = new int[width];

            for (int w = 0; w < width; w++)
            {
                  // fill in some initial values
                  // (filling in zeros would be more logic, but this is just for the example)
                  array2D[h][w] = w + width * h;
            }
      }

      return array2D;
    }

    int main()
    {
      printf("Creating a 2D array2D\n");
      printf("\n");

      int height = 15;
      int width = 10;
      int** my2DArray = create2DArray(height, width);
      printf("Array sized [%i,%i] created.\n\n", height, width);

      // print contents of the array2D
      printf("Array contents: \n");

      for (int h = 0; h < height; h++)
      {
            for (int w = 0; w < width; w++)
            {
                  printf("%i,", my2DArray[h][w]);
            }
            printf("\n");
      }

          // important: clean up memory
          printf("\n");
          printf("Cleaning up memory...\n");
          for (  h = 0; h < height; h++)
          {
            delete [] my2DArray[h];
          }
          delete [] my2DArray;
          my2DArray = 0;
          printf("Ready.\n");

      return 0;
    }


查看完整回答
反對 回復 2019-08-28
?
拉丁的傳說

TA貢獻1789條經驗 獲得超8個贊

該代碼不起作用,如果我們修復它,它不會幫助你學習正確的C ++。如果你做了不同的事情,那就更好了。原始數組(尤其是多維數組)很難正確地傳遞到函數和從函數傳遞。我認為從一個代表數組但可以安全復制的對象開始,你會好得多。查找文檔std::vector。

在您的代碼中,您可以使用vector<vector<int> >或者您可以使用36個元素模擬二維數組vector<int>。


查看完整回答
反對 回復 2019-08-28
?
慕標琳琳

TA貢獻1830條經驗 獲得超9個贊

使用指針的更好的替代方法是使用指針std::vector。這會處理內存分配和釋放的細節。

std::vector<std::vector<int>> create2DArray(unsigned height, unsigned width){
   return std::vector<std::vector<int>>(height, std::vector<int>(width, 0));}


查看完整回答
反對 回復 2019-08-28
  • 3 回答
  • 0 關注
  • 765 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號