簡體   English   中英

發送可變大小的2D數組以在C ++中運行

[英]Sending variable size 2D array to function in 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;
}

是什么導致此錯誤,如何將各種數組傳遞給函數?

我看到的問題

  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獲得該信息。

首先是int b[r][r]; 可變長度數組 ,在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;
    }
}

[N][M]的2D數組在內存中的布局與[N*M]的1D數組相同。

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

暫無
暫無

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

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