首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++中的Dereference指针

C++中的Dereference指针
EN

Stack Overflow用户
提问于 2013-01-20 14:41:40
回答 5查看 2.2K关注 0票数 2

所以我试着熟悉c++。下面是练习指针使用的任务。情况如下:

编写一个函数,提示用户输入他或她的名字和姓氏,作为两个单独的值。此函数应通过附加指针将两个值返回给调用方。只有当调用方传入姓氏的空指针时,它才会提示输入姓氏。

我试过几个版本。我现在被困的是:

代码语言:javascript
复制
#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。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2013-01-20 15:25:16

我认为这项工作的案文有错误,应改为:

编写一个函数,提示用户输入他或她的名字和姓氏,作为两个单独的值。此函数应通过附加指针将两个值返回给调用方。只有当调用方传入姓氏的非空指针时,才会提示输入姓氏。

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

代码语言:javascript
复制
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);
    }
}
票数 7
EN

Stack Overflow用户

发布于 2013-01-20 14:43:09

不要使用指针,这不需要指针。只需通过引用传递参数:

代码语言:javascript
复制
void getFullName(string& p_first, string& p_last) 

但是,问题是您正在取消引用p_last,即NULL ->未定义的行为:

代码语言:javascript
复制
if (!p_last) {  //this evaluates to true, because p_last==NULL
    cout << "Last name:";
    getline(cin, *p_last);
}
票数 0
EN

Stack Overflow用户

发布于 2013-01-20 14:50:47

考虑到您的问题说明您使用了附加项,我会将其写为:

代码语言:javascript
复制
string getFullName()
{
    string first, last;
    cout << "First name:";
    getline(cin, first);
    cout << "Last name:";
    getline(cin, last);
    return first + last;  // note use of additional
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14425591

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档