C 替换 & in C++
C replacement of & in c++
>我正在尝试用 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
}
相关文章:
- netcat command in c++
- Difference in displaying cv2 Mat
- C++ MFC Libraries in Travis CI
- 如何在OpenSSL中从configuration.h.in获取configuration.h
- 创建具有 new in 函数和"this is nullptr"异常的对象
- IN, OUT, INOUT Parameters
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 有人安装"IITB Simplecpp in mac"吗?
- 从 C 样式字符串中删除子字符串 "in place" 在C++代码中
- 如何修复"error: ‘_1’ was not declared in this scope"?
- Softmax Implementation in C++
- 将 out/in out 参数与 if/switch 的 init 语句一起使用
- IF-nesting in c++
- Gurobi GRBModel and GRBmodel in C++
- Tensorflow Hub in C++
- Centos7 g++ "to_string is not in a member of std"
- InitializeCriticalSectionEx Not Located In KERNEL32.Dll
- 将 lambda 表达式传递给 std::function in C++
- @CPPFLAGS@在 Makefile.in 中意味着什么?
- std::async from std::async in windows xp