我试图理解指针的基本原理,并编写了以下代码:
int c = 3;
int try(int a){
++a;
return 0;
}
int main(){
try(c);
printf("%d\n",c);
return 0;
}如何使用指针打印4?我知道我可以这样做:
int c = 3;
int try(int a){
++a;
return a;
}
int main(){
c = try(c);
printf("%d\n",c);
return 0;
}但我真的很想学习如何通过指针传递这些值。
此外,任何优秀的书籍推荐为坚实的C学习是永远欢迎。提前谢谢。
发布于 2022-04-27 16:34:10
这是如何做'c样式参考传递‘。
int tryIt(int *a){
++(*a);
}
int main(){
int c = 3;
tryIt(&c);
printf("%d\n",c);
return 0;
}将指针传递给变量,并在函数中取消对指针的引用。该函数有效地超出了其作用域来修改传递的变量。
请注意,我将c移到main中。在您的原始代码中,“try”可以修改c本身,因为它在全局范围内。
把“尝试”改为“tryIt”--因为这看起来很奇怪
发布于 2022-04-27 16:30:52
int c = 3;
void pass_by_ref(int *a) // Take a Pointer to an integer variable
{
++(*a); // Increment the value stored at that pointer.
}
int main(){
pass_by_ref(&c); // Pass the address of the variable to change
printf("%d\n",c);
return 0;
}https://stackoverflow.com/questions/72032260
复制相似问题