指针变为零C
Pointer becomes null c++
本文关键字:指针 更新时间:2023-10-16
我是C 的新手,这是我的指针变为null的代码,我在做什么错?
主要功能。
// 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.
指针可能不会或可能不为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 */);
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- 为什么++(*p)更改指针值
- 调整大小后指向元素值的指针unordered_map有效?
- 正在将指针转换为范围
- 使用指向成员的指针将成员函数作为参数传递
- 将OpenCV C++重写为EmguCV C#-如何使用指针
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错