zoukankan      html  css  js  c++  java
  • 二位数组传参及二位数组动态分配问题

    //二位数组参数传递
    
    //1.
    void display1(int arr[][4], const int rows)
    {
    	for (int i = 0; i < rows; i++)
    	{
    		for (int j = 0; j < 4; j++)
    		{
    			cout << arr[i][j] << ' ';
    		}
    		cout << endl;
    	}
    	cout << endl;
    }
    
    //2.
    void display2(int(*parr)[4], const int rows)
    {
    	for (int i = 0; i < rows; i++)
    	{
    		for (int j = 0; j < 4; j++)
    		{
    			cout << parr[i][j] << ' ';
    		}
    		cout << endl;
    	}
    	cout << endl;
    }
    //parr[i]等价于*(parr+i)
    
    
    //3.
    void display3(int **parr, const int rows, const int cols)
    {
    	for (int i = 0; i < rows; ++i)
    	{
    		for (int j = 0; j < cols; ++j)
    		{
    			cout << *((int*)parr + i * cols + j) << " ";   //注意:(parr+i*cols+j), 不是(arr+i*rows+j), 不能使用parr[i][j]
    		}
    		cout << endl;
    	}
    	cout << endl;
    }
    
    void display4(int **parr, const int rows, const int cols)
    {
    	for (int i = 0; i < rows; ++i)
    	{
    		for (int j = 0; j < cols; ++j)
    		{
    			cout << parr[i][j] << " ";
    		}
    		cout << endl;
    	}
    	cout << endl;
    }
    
    int main()
    {
    	int rows = 3;
    	int cols = 4;
    
    	int arr[][4] = { 0,1,2,3,4,5,6,7,8,9,10,11 }; 
    
    	display3((int**)arr, rows, cols);//不能使用display4
    	cout << "=======" << endl;
    
    	//动态二位数组
    	int **p;
    	p = new int*[rows];//创建行指针(数组指针)
    	for (int i = 0; i < rows; ++i)
    	{
    		p[i] = new int[cols]; //为每一行分配空间
    	}
    
    	for (int i = 0; i < rows; ++i)
    		for (int j = 0; j < cols; ++j)
    			p[i][j] = i * cols + j;
    
    	display4(p, rows, cols);
    
    	//删除行数组空间
    	for (int i = 0; i < rows; ++i)
    		delete[] p[i];
    
    	//删除行指针
    	delete[] p;
    	p = nullptr;
    
    
    	//一次性分配空间
    	int **p1;
    	p1 = new int*[rows];
    	p1[0] = new int[rows*cols];
    	for (int i = 0; i < rows; ++i)
    		p1[i] = p1[0] + cols*i;
    
    	for (int i = 0; i < rows; ++i)
    		for (int j = 0; j < cols; ++j)
    			p1[i][j] = i * cols + j;// 或者    *(p1[0]+i*cols+j) = i * cols + j;
    			
    
    	display4(p1, rows, cols);
    
    	display3((int**)p1[0], rows, cols);
    
    
    	delete[] p1[0];
    	delete[] p1;
    }
    

      

  • 相关阅读:
    安装一些好用的工具
    转:通过快键强制关闭 Ubuntu 上无响应的程序
    同步cm10.1源码时出现的一些错误的解决办法。
    repo sync的介绍翻译
    配置grub解决ubuntu12.04不能保存亮度和调节的问题
    给fcitx加上云拼音库
    自己安装配置ubuntu12.04过程(内容丰富)
    关于repo sync -j*的含义的猜测
    同步cm10.1的时候发生同步错误不能找到github上的文件
    Element-ui tree组件自定义节点使用方法
  • 原文地址:https://www.cnblogs.com/xslwm/p/10349842.html
Copyright © 2011-2022 走看看