线程1:xcode中的EXC\u错误访问(代码=1,地址=0x0)错误 我是一个业余程序员,在XCODE中学习如何使用C++,我一直在尝试创建一个程序,在那里你回答问题,根据你的答案,问题是不同的。问题是,我一直收到错误:线程1:EXC_BAD_ACCESS(code=1,address=0x0),我不知道是什么导致了它。这是我目前的代码: #include <iostream> #include <string> using namespace std; int main() { string name; cout << "what is your name "; getline (std::cin, name); string yes; cout << "ok, " << name << ", do you want to play a game? "; getline (std::cin, yes); cout << "\nno " << std::endl; string input =0; cin >> input; string Yes = "yes"; string No = "no"; if (input == No) { cout << "ok, sorry" << endl; } else if (input == Yes) { cout << " a question" << endl; } } #包括 #包括 使用名称空间std; int main(){ 字符串名; 库特溶液

线程1:xcode中的EXC\u错误访问(代码=1,地址=0x0)错误 我是一个业余程序员,在XCODE中学习如何使用C++,我一直在尝试创建一个程序,在那里你回答问题,根据你的答案,问题是不同的。问题是,我一直收到错误:线程1:EXC_BAD_ACCESS(code=1,address=0x0),我不知道是什么导致了它。这是我目前的代码: #include <iostream> #include <string> using namespace std; int main() { string name; cout << "what is your name "; getline (std::cin, name); string yes; cout << "ok, " << name << ", do you want to play a game? "; getline (std::cin, yes); cout << "\nno " << std::endl; string input =0; cin >> input; string Yes = "yes"; string No = "no"; if (input == No) { cout << "ok, sorry" << endl; } else if (input == Yes) { cout << " a question" << endl; } } #包括 #包括 使用名称空间std; int main(){ 字符串名; 库特溶液,c++,xcode,C++,Xcode,改变 string input =0; 到 而input将被构造为空字符串 那么刚才发生了什么? 调用编号为0的字符串构造函数。对于接受整数的字符串,没有直接构造函数,但 string(const CharT* s, const Allocator& alloc = Allocator() ); 足够接近。整数0被视为指向0的指针,NULL,而较差的字符串尝试从NULL指针构造自身。这意味着它将从NULL复制字符,直到找到以NULL字符结尾的字符串 幸运的是,“无处行

改变

string input =0;

input
将被构造为空字符串

那么刚才发生了什么? 调用编号为0的
字符串
构造函数。对于接受整数的字符串,没有直接构造函数,但

string(const CharT* s, 
       const Allocator& alloc = Allocator() );
足够接近。整数0被视为指向0的指针,
NULL
,而较差的
字符串
尝试从NULL指针构造自身。这意味着它将从
NULL
复制字符,直到找到以NULL字符结尾的字符串

幸运的是,“无处行踪”会很快停止,因为前几千字节的内存几乎总是被标记为“禁止进入区域”,当您尝试访问该区域中的任何位置时,程序就会崩溃。这使得空指针错误几乎可以立即检测到,并且很容易调试。只需等待程序崩溃,然后再运行b检查堆栈以查看空指针的来源。可能需要更多的工作才能找到它为什么为空,但是如果编程很简单,每个人都会这么做

为了验证这个假设,我创建了一个简单的类来模拟这种行为而不会崩溃

#include <iostream>

class test
{
public:
    test (const char * valp)
    {
        std::cout << "in char * constructor. Got: " << (void*) valp;
    }
};
int main() {
    test input =0;
}

被编译器成功地抓取为废话,拒绝。

代码>字符串输入=0;想知道你想在这里发生什么。此外,如果你是一个业余程序员,我建议读好的C++材料。没有C++书籍在任何代码示例中都有USER481301指出的错误,除非它是你的部分的一个键入。它要声明。“输入“作为代码其余部分的标识符。大部分都是随机拼凑而成的教程,所以我不完全确定。对不起。@j_lo2004--为什么要将字符串设置为“0”?请删除设置为“0”的内容。字符串是一个字符序列。通常您会在引号中指定某些内容。
string input=“这里没什么可看的。往前走。”;
给它指定一个数字是不寻常的。在这种情况下,这是致命的,因为一些非常巧妙的事情发生在幕后。我想我知道发生了什么,我正在做一些实验,看看我是否正确。
string(const CharT* s, 
       const Allocator& alloc = Allocator() );
#include <iostream>

class test
{
public:
    test (const char * valp)
    {
        std::cout << "in char * constructor. Got: " << (void*) valp;
    }
};
int main() {
    test input =0;
}
test input =1;