【问题标题】:Pointer becomes null c++ [duplicate]指针变为空c ++ [重复]
【发布时间】:2016-12-30 14:24:02
【问题描述】:

我是 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. 

【问题讨论】:

  • 您可能希望通过引用将参数传递给Login()
  • 你正在传递user,无处不在,价值。这意味着在该函数内设置user 绝对没有任何效果。您需要通过引用而不是值传递user。查看 C++ 书中有关按值传递函数参数与按引用传递函数参数的材料。
  • 你只是声明struct user_info *user;而不是分配它,所以它是NULL,但你很幸运,因为如果你不处于调试模式它可能包含垃圾并且执行你的代码是垃圾
  • 您也不应该尝试在std::vector 中获取元素的地址,然后继续使用它。 (这就是我认为您正在尝试做的事情,尽管是错误的)。对向量完全不相关的操作可能会导致它移动其内容,从而使您的指针无效。
  • 谢谢大家,我可以通过 malloc-ing 声明中的结构 + 使用 memcpy 而不是模型中的直接赋值来解决这个问题。

标签: c++ pointers vector function-pointers


【解决方案1】:

指针可能不为空,也可能不为空,但更重要的是它是未初始化的:

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.

编辑以下内容以使其工作安全感谢昆汀

这是因为您在调试模式下的编译器将其设置为 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 */);

【讨论】:

  • 啊,原始拥有指针...
猜你喜欢
  • 1970-01-01
  • 2011-10-01
  • 2013-01-09
  • 1970-01-01
  • 1970-01-01
  • 2018-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多