【问题标题】:c++ how to return a ptr to int from a pointer which is pointer to a structc ++如何从指向结构的指针返回一个ptr到int
【发布时间】:2018-07-13 18:04:34
【问题描述】:

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

【问题讨论】:

  • 请发布可编译的代码。你错过了;
  • 对不起,我不能发布整个代码,这只是其中的一部分。
  • 然后做一个小例子。

标签: c++ class pointers struct


【解决方案1】:

当心你的 find 函数将指针移动到内部列表,这是不好的。您应该使用私有变量,并返回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;
}

【讨论】:

  • 我从没想过for循环,让我的代码更整洁,谢谢
  • 我不太明白“return &node->value;”它返回地址的值?
  • 反之,返回值的地址。
【解决方案2】:

the_list 不是指向int 的指针,而是指向list_node 的指针,所以int *ptr = the_list; 不正确。

要获得指向该值的指针,请执行以下操作:

int *ptr = &(the_list->value);

【讨论】:

  • 顺便说一句,括号真的有必要吗?
  • int *ptr = &(the_list->value);意思是获取值包含的地址?
  • 是的,它就是这么做的。
  • &(any variable) 返回该变量的地址。
猜你喜欢
  • 2017-06-13
  • 1970-01-01
  • 2014-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-15
相关资源
最近更新 更多