gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:44:34 26 4
gpt4 key购买 nike

我正在尝试在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com