C++ 如何从指向结构的指针将 PTR 返回到 int
c++ how to return a ptr to int from a pointer which is pointer to a struct
我是 C++ 初学者,我在 C++ 实验室作业中遇到了问题。我不知道如何从指针返回指向 int 的指针,该指针指向结构的指针。
我的头文件
class list {
public:
/* Returns a pointer to the integer field
pointing to the first node found in list
with value val. Returns 0 otherwise */
int *find(int val);
private:
list_node *the_list;
}
我的 CPP 文件
int* list::find(int val)
{
while(the_list)
{
if(the_list->value == val)
{
// i try to return the pointer that is type pointer to int.
// the_list is a pointer to a struct type call list_node.
int * ptr = the_list;
return ptr;
}
the_list = the_list->next;
}
return 0;
}
struct list_node
{
int value; // data portion
list_node *next; // pointer next portion
list_node *previous; // pointer previous portion
};
the_list
不是指向int
的指针,而是指向list_node
的指针,因此int *ptr = the_list;
不正确。
若要获取指向该值的指针,请执行以下操作:
int *ptr = &(the_list->value);
请注意,
查找函数将指针移动到内部列表,这是不好的。您应该使用私有变量,并返回value
成员的地址:
int* list::find(int val)
{
for(list_node *node = the_list; node != nullptr; node = node->next)
{
if(node->value == val)
{
// i try to return the pointer that is type pointer to int.
// the_list is a pointer to a struct type call list_node.
return &node->value;
}
}
return nullptr;
}
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- C++中的指针否定 (!ptr == NULL)
- 使用 void 指针:void **ptr.. 如何修改共享内存的值?
- C++ 如何从指向结构的指针将 PTR 返回到 int
- 正确使用std智能指针以确保ptr安全
- 一个唯一的ptr类如何将它的实例指针传递给它的成员对象
- openv Ptr类.指针对象在调用函数后被删除