簡體   English   中英

為二維數組動態分配內存時出錯

[英]Error While dynamically allocating memory for a two - D array

我正在實現一個二維數組動態內存分配。 編譯程序時出現錯誤。 代碼如下:

   # include<iostream>
   # include<stdio.h>
   # include<conio.h>
   # include<stdlib.h>
   # define COLS 5
   using namespace std;

   typedef int Rowarray[COLS];
   int main()
   {
      Rowarray *rptr;
      int nrows=3;
      int row,col;
      rptr=(int**)malloc(nrows * COLS * sizeof(int)) ; // Error Line
      for(row=0;row<nrows;row++)
      { static int i=0;
        for(col=0;col <COLS;col++,i++)
        {
          rptr[row][col]=i;
        }
      }  
      for(row=0;row<nrows;row++)
      { 
        for(col=0;col <COLS;col++)
        {
          cout << "\n" << rptr[row][col];
        }
      }     
     getch();  
     return 0;
   }

我得到的錯誤是cannot convert int**' to賦值` cannot convert int**' to int(*)[5]'

如果您用普通的new替換丑陋的malloc

rptr= new Rowarray[nrows];

您的程序會編譯甚至運行。 並且不要忘記delete [] rptr;

但是為什么不使用向量呢?

#include <vector>
//...
std::vector<std::vector<int> >rptr;

您的語法錯誤,並且C / C ++始終不允許您轉換為數組類型。

您的Rowarray可能應該是int**的typedef,因此您可以說:

rptr=(int**)malloc(nrows * COLS * sizeof(int)) ; 

更一般而言,除非您因家庭作業或其他原因而對您有要求,否則這樣做是一種過於困難的方法。 無需使用malloc和原始指針,您可以使用std::vector<std::vector<int> >輕松創建動態二維數組

嘗試刪除malloc左側的演員表(括號)。 如果這樣不起作用,請用(Rowarray *)替換它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM