我们知道无法直接通过new来申请一个二维的堆内存数组,于是有人想出了一个办法:创建一个一维堆内存指针数组,即每个数组元素是一个指针,原后用new给各个指针分配一个一维的堆内存数组,那么最后表示出来就像是一个二维的堆内存数组了。试编写一段程序,依照以上方法实现一个大小为8x8的二维堆内存数组,数据类型为整型,并将数组元素依次赋值、输出。
运行结果示例:
0 1 2 3 4 5 6 7 8
.
.
.
.
.
.
.57 58 59 60 61 62 63
#include<iostream.h>
void main(void)
{
int *p[8];
int **pp=p;
*pp=new int[8];
for(int i=0;i<8;i++)
{
for(int j=0;j<8;j++)
{
*(*(pp+i)+j)=i*8+j;
cout<<*(*(pp+i)+j)<<' ';
}
cout<<endl;
}
delete [] pp;
}  //运行出现内存不可写,为什么????????
只能运行得出0 1 2 3 4 5 6 7 后面的出现内存不可读

解决方案 »

  1.   

    #include <iostream.h> 
    void main(void) 

    int *p[8]; 
    int **pp=p; 
    for(int i=0;i <8;i++) 

    pp[i]=new int[8];//空间应该要在这里new出来,如果在for之前new的话,那就只New出来8个Int了。所以就出现你之前的错误
    for(int j=0;j <8;j++) 

    *(*(pp+i)+j)=i*8+j; 
    cout <<*(*(pp+i)+j) <<' '; 

    cout <<endl; 

    for(i=0;i<8;i++) delete [] pp[i]; //你不能直接把pp给删除了,而是要一个一个把你New来的空间删除,而pp指向了*p[8],这个将由系统自己删除
             
    }  
      

  2.   

    为什么要这样写呢??自己写个类不是更好吗??#ifndef MYARRAY_H
    #define MYARRAY_Htemplate <class T>
    class CMyArray  //二维数组
    {
    public:
    CMyArray(int row, int col);

    ~CMyArray(); T& operator()(int row, int col); //访问第row行,col列的元素private:
    T* m_pData; //数组指针
    int m_iRow; //行
    int m_iCol; //列
    };template <class T>
    CMyArray<T>::CMyArray(int row, int col)
    {
    m_pData = new T[row * col]; //申请row * col 大小的空间
    m_iRow = row;
    m_iCol = col;
    }template <class T>
    CMyArray<T>::~CMyArray()
    {
    if (m_pData)
    delete[] m_pData;
    }template <class T>
    T& CMyArray<T>::operator ()(int row, int col)
    {
    return m_pData[row * m_iCol + col];
    }
    #endif#include "stdafx.h"
    #include "MyArray.h"int _tmain(int argc, _TCHAR* argv[])
    {
    #define MAX_ROW 8   //行
    #define MAX_COL 8   //列 CMyArray<int> arr(MAX_ROW, MAX_COL);
    //设置数据
    for (int i = 0; i < MAX_ROW; i++)
    for (int j = 0; j < MAX_COL; j++)
    {
    arr(i, j) = i * 8 + j;
    }
    //输出
    for (int i = 0; i < MAX_ROW; i++)
    {
    for (int j = 0; j < MAX_COL; j++)
    printf("%4d", arr(i, j));
    printf("\n");
    } getchar();
    return 0;
    }
      

  3.   

    当然不对,你只new了前8个而已
      

  4.   

    void main(void) 

    int *p[8]; 
    int **pp=p; 
    *pp=new int[8]; 
    for(int i=0;i <8;i++) 

    for(int j=0;j <8;j++) 

    *(*(pp+i)+j)=i*8+j; 
    cout < <*(*(pp+i)+j) < <' '; 

    cout < <endl; 

    delete [] pp; 直接new p[64];所谓的平坦模式(其实无意义,与dos已经无关了)。如果你要做成指针的指针,如下
    int** pp[8];for(i-8)
    {
       int* p=new int[8];
       *pp[i]=p;//大约是这个意思,似乎需要测试一下。
        for (j-8)
        对p进行操作即可}