【发布时间】: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