gpt4 book ai didi

c++ - 在 C++ 中取消引用 NULL 指针

转载 作者:搜寻专家 更新时间:2023-10-31 00:00:00 26 4
gpt4 key购买 nike

所以我正在尝试熟悉 C++。这是应该练习指针使用的任务。事情是这样的:

Write a function that prompts the user to enter his or her first name and last name, as two separate values. This function should return both values to the caller via additional pointer. It should prompt for the last name only if the caller passes in a NULL pointer for the last name.

我试过几个版本。我现在坚持的是:

#include <iostream>
#include <string>

using namespace std;


void getFullName(string *p_first, string *p_last) {
cout << "First name:";
getline(cin, *p_first);
if (!p_last) {
cout << "Last name:";
getline(cin, *p_last);
}
}


int main() {

string first;
string *p_first = &first;
string *p_last = NULL;

getFullName(p_first, p_last);

cout << *p_first << endl << *p_last << endl;
return 0;
}

嗯,它崩溃了。我试图传递对“最后”的引用,然后指向它。但在退出函数后,指针再次为 NULL。

最佳答案

我认为练习文本中有错误,应该是:

Write a function that prompts the user to enter his or her first name and last name, as two separate values. This function should return both values to the caller via additional pointer. It should prompt for the last name only if the caller passes in a non-NULL pointer for the last name.

就目前而言,您的代码通过取消引用空指针导致未定义的行为

void getFullName(string *p_first, string *p_last) {
cout << "First name:";
getline(cin, *p_first);
if (!p_last) { /* <-- This test should be inverted */
cout << "Last name:";
/* Now, you get here only when p_last == NULL. On the next line,
* you dereference that null-pointer and try to read a string into
* non-existing memory: recipe for disaster.
* With the condition inverted, you would only get here if you have
* a string to store the text in. */
getline(cin, *p_last);
}
}

关于c++ - 在 C++ 中取消引用 NULL 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14425591/

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