C++ C更换&;在c++;
我试图在C中创建一个函数来传递最后一个节点的K,但我很难找到一个替换C++中的&操作符的方法,该操作符是一个引用。 我知道我应该用*来切换&,但它似乎对我来说仍然不起作用C++ C更换&;在c++;,c++,c,list,replace,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); po
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
是指针(头也是指针)。当您想要访问它引用的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
}
如果(pos==k)
,编译器没有警告您这一点吗?@alk我会感到惊讶。发布的片段有很多问题,不仅仅是将int
与指针进行比较。k_to_last(head->next,k,&pos)代码>应该是k_到最后一个(head->next,k,pos)代码>因为此时pos
已经是一个指针pos++
增加指针的值,而不是指针指向的值,您需要取消对它的引用++(*pos)
。与pos==k
相同。我认为您会感到困惑,因为您将namepos
用于int
变量和指向int
变量的指针。名称指针类似于代码> PyPOS < /C>。替换C++中的&操作符,这是什么?你可以编译使用C++的指针而不改变任何‘&’- <代码>和<代码>操作符,C++是C.继承的“地址”(符号在类型和表达式上有不同的含义)。