fra*_*nkc 12 c++ arrays static-analysis
请考虑以下代码段:
#include <iostream>
using namespace std;
int a[10][2];
int b[10][2];
int main(){
//intended
cout << a[0][0] - b[0][0] << endl;
//left out dimension by mistake
cout << a[0] - b[0] << endl;
}
Run Code Online (Sandbox Code Playgroud)
显然(或者可能不是每个注释)第二种情况是C和C++中的有效指针算法,但在我使用它的代码库中通常是语义错误; 通常在嵌套的for循环中省略了维度.有没有-W标志或静态分析工具可以检测到这个?
您可以使用std::array哪个不允许:
using d1=std::array<int, 2>;
using d2=std::array<d1, 10>;
d2 a;
d2 b;
std::cout << a[0][0] - b[0][0] << endl; // works as expected
std::cout << a[0] - b[0] << endl; // will not compile
Run Code Online (Sandbox Code Playgroud)