c++ - C++ 中 & 的 C 替换

标签 c++ c list replace

我正在尝试在 C 中创建一个函数来传递最后一个节点的 K,但我很难在 c++ 中找到 & 运算符的替代品这是一个引用。 我知道我应该用 * 切换 & 但它似乎仍然不适合我。

my_node *k_to_last(my_node * head, int k, int *pos)
{
    if (head == NULL)
        return NULL;
    my_node *current = k_to_last(head->next,k, &pos);
    pos++;
    if (pos == k)
        return head;
    return current;
}

int main ()
{
    int k;
    int pos = 0;
    printf("\nEnter the K node: ");
    scanf("%d", &k);
    printf("\nthe %d node value from last is: %d\n", k_to_last(head, k, &pos)->value);
    return 0;
}

感谢您提前提供的任何帮助,请忽略一些小问题,例如使用 scanf 而不是 fget 等......

编辑:非常感谢“JeremyP”的回答 固定代码:

my_node *k_to_last(my_node * head, int k, int *pos)
{
if (head == NULL)
    return NULL;
my_node *current = k_to_last(head->next, k, pos);
(*pos)++;
if (k == *pos)
    return head;
return current;
}

int main()
{
    int k;
    int pos = 0;
    printf("\nEnter the K node: ");
    scanf("%d", &k);
    printf("\nthe %d node value from last is: %d\n", k, k_to_last(head, k, &pos)->value);

    return 0;
}

最佳答案

* 在此上下文中表示“指针”。与 C++ 引用不同,类似于 DIY 引用的指针不会自动取消引用。所以在声明中

my_node *k_to_last(my_node * head, int k, int *pos)

pos 是一个指针(head 也是)。当您想要访问它引用的 int 时,您必须显式取消引用它,例如

if (k == *pos) // Note the *
{
    // do somenthing
}
(*pos)++; // increment the int to which pos points

此外,要将 int 传递给 pos 函数,您必须使用 & 运算符获取其地址。

int pos = 0;
my_node head; // Gloss over the fact that this is uninitialised
k_to_last(&head, k, &pos);

但在函数内部,由于 pos 已经是一个指针,因此对于需要 int* 的参数,例如在调用时,不需要获取其地址该函数递归地执行。

my_node *k_to_last(my_node * head, int k, int *pos)
{
    if (head == NULL)
        return NULL;
    my_node *current = k_to_last(head->next,k, pos); // no & needed here
}

关于c++ - C++ 中 & 的 C 替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48059588/

相关文章:

C++ 重复符号链接(symbolic link)器错误与适当的包含保护?

c++ - boost asio ssl async_shutdown总是以错误结束?

c - clang 编译器中用于定义预处理器使用的宏的标志是什么?

java - 在使用泛型而不是原始类型时实现 List 而不是 ArrayList

c++ - 将 boolean 值列表转换为 _int64

c++ - 如何在运行时查看 C 程序的内存布局?

c++ - 模板函数的差异

c - 为某种类型分配更少的空间?

c - 结构指针总是被初始化为 nil

python 按值而不是按引用列出