這個問題在這里已經有了答案: 為什么可變長度陣列不是 C 標準的一部分? (13 個回答) 昨天關門。
代碼
#include <iostream>
void display(int, int, void* );
int main()
{
int A[][2]= { 0, 2,
4, 2,
2, 2};
int m=3, n=2;
display(m, n, &A[0][0]);
}
void display(int m, int n, void *p)
{
int (*q)[m][n]=( int(*)[m][n] )p; // This causing error
for(int i=0; i<=m-1; i )
{
for(int j=0; j<=n-1; j )
{
std::cout<<q[i][j]<<" ";
}
std::cout<<"\n";
}
}
輸出(錯誤)
Cannot initialize a variable of type 'int (*)[m][n]' with
an rvalue of type 'int (*)[m][n]'
https://stackoverflow.com/a/35657313/11862989這里用戶提到了這一點,但它不起作用。
int (*q)[m][n]=( int(*)[m][n] )p; 那么為什么沒有發生這種型別轉換。
uj5u.com熱心網友回復:
您不必為靜態大小的資料使用向量,您仍然可以使用“C”樣式的陣列。并且您可以以型別安全(和記憶體訪問安全的方式)執行此操作,如下所示:
#include <iostream>
/*
This is an insecure way of doing things anyway since it depends on
- typeconversion from void* (you could put anything into this function and it would try to display it)
- n and m could differ from actual sizes of the array leading to out of bounds error
void display(int m, int n, void* p)
{
int(*q)[m][n] = (int(*)[m][n])p; // This causing error <== because it is incorrect syntax
for (int i = 0; i <= m - 1; i )
{
for (int j = 0; j <= n - 1; j ) // dont compare with <= it just not standard practice
{
std::cout << q[i][j] << " ";
}
std::cout << "\n";
}
}
*/
// this would be the fixed size signature
// note it is typesafe (no void*) and carries the sizes
// within the datatype
void display(int (&values)[3][2])
{
for(int row=0; row < 3; row)
{
for(int col=0; col < 2; col)
{
std::cout << values[row][col] << " ";
}
std::cout << "\n";
}
}
// to make the previous function reusable for other array sizes
// you can make it a function template
// and notice I replaced the index based for loops with range
// based for loops for added safety
template<std::size_t N, std::size_t M>
void display_template(int (&values)[N][M])
{
std::cout << "\nfunction template version of display\n";
// need a reference to a row
// and the consts mean that display can only
// look at the rows and values not change them
for(const auto& row : values)
{
for(const auto value : row)
{
std::cout << value << " ";
}
std::cout << "\n";
}
}
int main()
{
// initialize 2d array in a 2d manner (nested {})
int values[3][2] {{0,2},{4,2},{2,2}};
display(values);
display_template(values);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/409918.html
標籤:
