【发布时间】:2021-04-25 21:08:18
【问题描述】:
所以我想做一个递归函数,将一个数字乘以 2。它适用于按值调用。我的问题是我不能使用引用调用。我的意思是它会编译,但我会收到警告。至少我不知道如何正确地做到这一点,也许你可以帮助我?
#include <stdio.h>
#include <stdlib.h>
int *rekursion(int *n){
if((*n) > 1000){
return 0;
}
printf("%d\t",(*n));
return rekursion((*n)*2);
}
int main() {
int n = 10;
rekursion(&(n));
printf("%d",n);
return 0;
}
Error:
test16.c:15:22: warning: passing argument 1 of 'rekursion' makes pointer from integer without a cast [-Wint-conversion]
15 | return rekursion((*n)*2);
| ~~~~^~
| |
| int
test16.c:9:21: note: expected 'int *' but argument is of type 'int'
9 | int *rekursion(int *n){
提前致谢!
【问题讨论】:
-
抱歉
-
好吧,在你的主函数中你传递了一个指针,而在函数中你传递了一个整数。为什么还要通过引用传递它?
-
return rekursion((*n)*2);应该做什么?(*n)*2取消引用指针并乘以 2。但这不是rekursion()函数所期望的指针。你想在调用函数之前加倍*n吗? -
确实如此,我现在看到了。我只是想参考一下,有没有办法参考一下?
-
所以我想将 n 的值加倍,只是我可以在休息后在我的主函数中执行 printf。
标签: c pointers recursion pass-by-reference