c++ - 如何访问指针结构的成员变量?
问题描述
我有一段时间没有用 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;
}
解决方案
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;
}
推荐阅读
- java - 爪哇。计算正确的变化
- apache-spark - 如果作业花费的时间比预期的长,则终止 Spark 作业或终止 EMR 集群
- angular - 选择选项并在其他下拉菜单中禁用相同的选项
- afp - 如何在 C# 或 Java 中获取 AFP 文件的页数
- python - 更改python中的字典字典
- c# - 如何在活动中调用 Owin StartUp?
- c - 文件夹内的xcode c文件未执行
- c# - 在响应 302 的位置注销重定向 URI 后丢失
- python - 解密后的令牌不包含任何东西,Python
- python - 即使在名称冲突的情况下,pip 也可以从 PyPi 上的私有索引中选择包?