C++ 如何从指向结构的指针将 PTR 返回到 int

c++ how to return a ptr to int from a pointer which is pointer to a struct

本文关键字:指针 PTR 返回 int 结构 C++      更新时间:2023-10-16

我是 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;
}