[英]2d array with index input function in c++
我在 function 中的輸入數組有問題; 在這段代碼中,我從用戶那里獲取一個帶有索引的數組參數,function 將打印帶有參數保留的二維數組表; 這是代碼:
#include <iostream>
#include <windows.h>
using namespace std ;
const char * table[3][2]={{"m1","m2"},{"n1","n2"},{"h1","h2"}} ;
void setTable(char *array,int n,int m) {
for(int i=0 ; i<n;i++){
for(int j=0 ; j<m;j++) {
cout<<array[i][j]<<"---" ; //print array
}
}
}
int main(){
setTable((char * )table,4,2) ; // send array with indexes to function
return 0;
}
但是當我運行它時出現錯誤:
In function 'void setTable(char*, int, int)':
[Error] invalid types 'char[int]' for array subscript
arrays 數組不能簡單地轉換為單個指針。
通常,當您需要進行 C 風格的轉換時(例如在(char * )table
),您應該將其視為您做錯了什么的標志。
現在要解決您的問題...您必須記住 arrays 自然衰減為指向其第一個元素的指針。 也就是說, table
衰減到&table[0]
。 這將具有類型“指向兩個指向char
的指針的數組的指針”。 或char* (*) [2]
。
所以參數需要聲明為
char* (*array)[2]
然后在調用 function 時只需傳遞table
:
setTable(table, 3, 2);
如果您使用標准 C++ 類和類型別名,那么它會更簡單:
using table_type = std::array<std::array<std::string, 2>, 3>;
table_type table = { ... };
void setTable(table_type& table) { ... }
當然我不推薦使用全局變量,但如果你使用它們,你甚至不需要將它們作為 arguments 傳遞給你的函數。
將 C 樣式的二維數組傳遞給 function 時,function 需要知道數組維度才能正確進行索引。
喜歡:
const char * table[3][2]={{"m1","m2"},{"n1","n2"},{"h1","h2"}} ;
void setTable(const char * array[][2],int n,int m) {
for(int i=0 ; i<n;i++){
for(int j=0 ; j<m;j++) {
cout<<array[i][j]<<"---" ;
}
}
}
int main(){
setTable(table,4,2) ;
return 0;
}
順便說一句:考慮使用 C++ 容器std::vector
而不是 C 樣式數組
#include <iostream> using namespace std; const char* table[3][2] = {{"m1","m2"},{"n1","n2"},{"h1","h2"}}; template <typename T, int n, int m> void setTable(T (&arr)[n][m]) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cout << arr[i][j] << "---"; //print array } cout << '\n'; } } int main() { setTable(table); // send array with indexes to function return 0; }
嘗試將“array”重命名為其他單詞,例如“table”。 我相信視覺工作室保留了“數組”這個詞。
您需要將 function 參數從char*
轉換為之一char**
const char * arr[][2]
:按值傳遞數組,這將導致衰減到第一個維度(即維度 3)的指針類型。 (參考)const char * (&arr)[3][2]
:通過引用傳遞數組將確保第一個維度不會衰減。 (參考)const char* (*arr)[3][2]
:傳遞一個指向數組本身的指針,它保留維度,因為第一個維度已經是指針類型。 這還需要在打印時傳遞setTable(&arr...)
並通過(*arr)[i][j]
取消引用指針。#include <iostream>
// void setTable(const char * arr[][2],int n,int m) {
// void setTable(const char* (*arr)[3][2],int n,int m) { // need to use setTable(&table, 4, 2) and (*arr)[i][j]
void setTable(const char * (&arr)[3][2],int n,int m) {
for(int i=0 ; i<n;i++){
for(int j=0 ; j<m;j++) {
std::cout<<arr[i][j]<<"---" ; //print array
}
std::cout << "\n";
}
}
int main(){
const char * table[3][2]={{"m1","m2"},{"n1","n2"},{"h1","h2"}} ; // 2d array(3x2) of const char*
setTable(table,3,2) ; // send array with indexes to function
return 0;
}
最后,正如其他答案中提到的那樣,使用標准 C++ 容器(例如std::array
)是避免數組到指針衰減的好主意。 此外,您應該避免using namespace std
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.