Is there a way to implement that sort of Code
#include<stdio.h>
void func(int a)
{
a++;
}
int main()
{
int a=0;
func(a);
printf("%d", a);
return 0;
}
The changes I have made to the variable a dont seem to carry over when I reuse it in the main function. I think its done by using static variables but i cant figure out how to do it
you need a 'c style pass by reference'
void func(int *a)
{
(*a)++;
}
and
func(&a);
ie - pass in the address of 'a' as a pointer, then update it by dereferencing the pointer
If a
is passed by copy (like in this case), changes made by your functions will not affect the variable in your main
. You should pass this parameter by reference.
So the solution must be like the following one
#include<stdio.h>
void func(int* a) {
(*a)++;
}
int main()
{
int a=0;
func(&a);
printf("%d", a);
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.