首页 > 解决方案 > 如何访问指针结构的成员变量?

问题描述

我有一段时间没有用 C++ 编程了,所以我一直在努力改进。我有一个非常简单的登录功能,但是它不起作用。login 函数调用getUserAttempts()返回一个指向包含用户详细信息(如用户名和密码)的结构的指针。但是,每当我尝试访问指针的结构变量时,程序就会崩溃。我觉得我错过了一些明显的东西,但不能指望它。

#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <unordered_map>

typedef std::unordered_map<std::string, std::string> unorderedMap;

typedef struct Credentials {
    std::string username;
    std::string password;
} structCred;

void login();
structCred* getUserAttempts();


void login() {  
    unorderedMap credentialMap;
    credentialMap["username"] = "mypassword123";
    structCred *p;

    for (int i = 0; i < 3; i++) {
        p = getUserAttempts();
        auto it = credentialMap.find(p->username);
        std::cout << it->first;
        std::cout << it->second;
    }
    return;
}


structCred *getUserAttempts() {
    structCred credentialAttempt;
    std::string username, password;
    std::cout << "Please enter your username: ";
    std::getline(std::cin, credentialAttempt.username);
    std::cout << "Please enter your password: ";
    std::getline(std::cin, credentialAttempt.password); 
    return &credentialAttempt;
}


int main() {
    std::cout << "Welcome..." << std::endl;
    login();
    return 0;
}

标签: c++

解决方案


return &credentialAttempt;

这将返回一个指向函数局部变量的指针credentialAttempt。这不起作用,因为函数 local 在函数返回时立即被销毁,因此该函数正在返回一个指向不再存在的指针。因此,取消引用返回的指针是未定义的行为。

相反,只需按值返回对象:

structCred getUserAttempts() {
    structCred credentialAttempt;
    std::string username, password;
    std::cout << "Please enter your username: ";
    std::getline(std::cin, credentialAttempt.username);
    std::cout << "Please enter your password: ";
    std::getline(std::cin, credentialAttempt.password); 
    return credentialAttempt;
}

推荐阅读