我有像
这样的代码 #include <iostream>
int main() {
int** array = new int*[2];
int row1;
int row2;
int answer;
std::cout << "Type 1 to create the 2d array: ";
std::cin >> answer;
std::cout << std::endl;
if (answer == 1) {
array[0] = new int[0];
array[1] = new int[0];
std::cout << "Fill the first array row: ";
std::cin >> row1;
std::cout << std::endl;
std::cout << "Fill the second row: ";
std::cin >> row2;
array[0][0] = row1;
array[1][0] = row2;
}
else
{
std::cout << "No arrays created";
}
// Here I test if the array[0][0] was created but when the answer is not 1,but 2
// it should ignore the if-statement at the bottom but it still execute's it
// and my debugger get an application error
// So is there an other way to test if an array was created ,no vectors.
// I have to do it with arrays :P
if (array[0][0] > 0)
{
std::cout << "1." << array[0][0] << " 2." << array[1][0] << std::endl;
}
return 0;
}
我应该使用什么而不是(array[0][0] > 0)
如果我使用2作为答案,程序仍然执行底部if语句并且调试器得到应用程序错误,但是当答案为1时一切都很好。为什么它仍然执行底部的if语句?
我更新了代码
答案 0 :(得分:3)
好的,我不知道我是否理解你的问题,但这取决于结构:
内存:
int *array = 0; //=nullptr
if (array==0) or if (array==nullptr)
载体:
vector<Obj> v;
if (v.empty())
列表:
list<Obj> l;
if (l.empty())
这取决于结构。
注意:直接创建结构时,没有指针,它会自动创建
vector<Obj> a; //Called to the constructor
vector<Obj>* a = 0; // It is not created check with if(!a)