我是C ++的新手,这是我的指针变为空的代码,我做错了什么?
主要功能。
// in main() function
switch (UserView::RequestMainMenuOption()) {
case 1:
{
struct user_info *user; // the pointer in question.
if (UserController::Login(user) && user) { // shows null here
std::cout << user->username << std::endl; // this line does not execute.
控制器。
bool UserController::Login(struct user_info *user)
{
//...
// std::cin username / password and validate in the user model.
if (User::ValidateCredentials(username, password, user)) {...}
}
模型。
int User::ValidateCredentials(std::string username, std::string password, struct user_info *user)
{
// UserList is a vector of struct user_info that contains std::string username, password;
std::vector<user_info> UserList = User::GetUserList();
// index is searched for here based on credentials...
// address of the element in the user list is assigned to user.
user = &UserList.at(index);
// address is successfully assigned (tested)
// but when returning back to the first function call in the main() function, user is NULL.
答案 0 :(得分:0)
指针可能不是或可能不是null,但更重要的是它未初始化:
struct user_info *user /* = ???? initialise here */; // the pointer in question.
if (UserController::Login(user) && user) { // shows null here
std::cout << user->username << std::endl; // this line does not execute.
由于Quentin
,编辑以下内容使其安全工作这是因为您在调试模式下的编译器将其设置为null ..您想要:
std::unique_ptr<user_info> user = std::make_unique<user_info)>(/* constructor arguments go here */);
或者如果共享对象:
std::shared_ptr<user_info> user = std::make_shared<user_info)>(/* constructor arguments go here */);