2015-12-09 127 views
0

我正在尝试编写一个可变大小数组并打印它的函数。但我在编译时在函数声明参数列表中有问题。发送可变大小2D数组以在C++中运行

的错误是:

cannot convert ‘int (*)[(((sizetype)(((ssizetype)r) + -1)) + 1)]’ to ‘int**’ for argument ‘1’ to ‘void printHalf(int**, int, int)’ 
    printHalf(b, r, r); 

代码:

#include <iostream> 

using namespace std; 

void printHalf(int **a, int row, int col) { // Problem is here. 
    for(int i=0; i < row; i++) { 
     for(int j=0; j < col; j++) { 
      if(i <= j) { 
       cout << a[i][j] << " "; 
      } 
     } 
     cout << endl; 
    } 
} 

int main() { 
    int r; 
    cout << "No. of rows: "; 
    cin >> r; 
    int b[r][r]; 

    for(int i=0; i < r; i++) { 
     for(int j=0; j < r; j++) { 
      cin >> b[i][j]; 
     } 
    } 

    printHalf(b, r, r); 
    return 0; 
} 

是什么原因造成这个错误,以及我如何通过各种阵列的功能?

+0

@coincoin我认为你应该在C++中使用'new []'而不是'malloc()'。 – MikeCAT

+0

我认为你应该既不使用也使用'std :: vector'。 – TartanLlama

+0

不要在C++中编写C代码 – ForeverStudent

回答

2

首先关闭int b[r][r];variable length array并且在C++中不是标准的。如果需要,可以在运行时再调整大小的容器,我建议你使用std::vector

std::vector<std::vector<int>> data(r, std::vector<int>(r, 0)); // create vector and set all elements to 0 

然后打印功能将成为

void printHalf(const std::vector<std::vector<int>>& data) { 
    for(std::size_t i=0; i < data.size(); i++) { 
     for(std::size_t j=0; j < data[i].size(); j++) { 
      if(i <= j) { 
       cout << a[i][j] << " "; 
      } 
     } 
     cout << endl; 
    } 
} 
+0

使用引用来避免复制许多数据可能是好的。 'void printHalf(std :: vector > data)' - >'void printHalf(const std :: vector >&data)' – MikeCAT

+0

@MikeCAT已经修复它 – NathanOliver

+1

我也会建议仅使用平坦/线性'矢量'而不是嵌套矢量'矢量>'。 – coincoin

2
[N][M]

二维阵列布置在同一内存作为[N*M]的一维数组。

void printHalf(int *a, int row, int col) { // Problem is here. 
    for(int i=0; i < row; i++) { 
     for(int j=0; j < col; j++) { 
      if(i <= j) { 
       cout << a[i*col+j] << " "; 
      } 
     } 
     cout << endl; 
    } 
} 

然后你可以给它打电话printHalf(&b[0][0], r, r)

你根本的误解是数组和指针之间的关系。数组不是指针。一个int**可以被看作是一个int*的数组,这不是你所拥有的。 b[0]给你一个int[r]。这与int*不同。 b[0][0]让你第一个int

+0

你会想'a [i * col + j]' – Pixelchemist

+0

@Pixelchemist固定。 – Simple

+0

谢谢你给我C面向的答案,但我猜矢量是去C++的方式 –

3

问题,我看到

  1. C++不允许可变长度数组的声明。因此,

    int b[r][r]; 
    

    是错误的。

  2. 一维数组衰减为指针,但二维数组不会衰减为指向指针的指针。即使你有b正确定义,如:

    int b[10][10]; 
    

    不能使用b作为参数给需要int**的功能。

解决方案

我建议使用std::vector

std::vector<std::vector<int>> b(r, std::vector<int>(r)); 

相应地更改功能printHalf

void printHalf(std::vector<std::vector<int>> const& b) { ... } 

你不需要rowcol作为参数,因为这些信息可以从std::vector获得。