gpt4 book ai didi

c++ - Printf - 访问冲突读取位置 - C++

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:57:50 25 4
gpt4 key购买 nike

0xC0000005: Access violation reading location 0xcccccccc.

printf 抛出这个异常。

我不知道为什么会这样...这些字符串变量中有值。我用错了 printf 吗?

帮助! (请看开关盒)

string header;
string body;
string key;

if (!contactList.isEmpty()) {

cout << "Enter contact's name: ";
getline(cin, key);
Contact * tempContact = contactList.get(key);
if (tempContact != NULL) {
string name = tempContact->getName();
string number = tempContact->getNumber();
string email = tempContact->getEmail();
string address = tempContact->getAddress();

//I've just put this here just to test if the variables are being initialized
cout << name + " " + number + " " + email + " " + address << endl;

switch (type) {
case 1:
printf("%-15s %-10s %-15s %-15s\n", "Name", "Number", "Email", "Address");
printf("%-15s %-10s %-15s %-15s\n", name, number, email, address);
break;
case 2:
printf("%-15s %-10s\n", "Name", "Number");
printf("%-15s %-10s\n", name, number);
break;
case 3:
printf("%-15s %-15s\n", "Name", "Email");
printf("%-15s %-15s\n", name, email);
break;
case 4:
printf("%-15s %-15s\n", "Name", "Address");
printf("%-15s %-15s\n", name, address);
break;
default:
printf("%-15s %-10s %-15s %-15s\n", "Name", "Number", "Email", "Address");
printf("%-15s %-10s %-15s %-15s\n", name, number, email, address);
}

} else {
cout << "\"" + key + "\" not found.\n" << endl;
wait();
}

} else {
cout << "Contact list is empty.\n" << endl;
wait();
}

第一个 printf 打印正常,但第二个会抛出异常,似乎与我如何传递字符串值无关。

最佳答案

printf 的“%s”需要一个 char* 作为参数,而不是 std::string。因此 printf 会将您的字符串对象解释为指针并尝试访问对象的第一个 sizeof(char*) 字节给出的内存位置,这会导致访问冲突,因为这些字节并不是真正的指针.

要么使用字符串的 c_str 方法获取 char*,要么不使用 printf。

关于c++ - Printf - 访问冲突读取位置 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2217148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com