C 替换 & in C++

C replacement of & in c++

本文关键字:C++ in 替换      更新时间:2023-10-16

>我正在尝试用 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: %dn", 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: %dn", 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
}