Help with pointers

I need your help.
With this code, I get these results:
1)a=3,b=9,c=14
2)a=3,b=3,c=6

I understand the first one. But not the second one. Isn't it supposed to be a=1,b=3,c=6 ?

[code]
#include <iostream>
#include<cstdlib>
#include<stdio.h>
using namespace std;

int f1(int a, int* b)
{
int c=0;
*b=9;
c=a+*b+2;
return c;
}

int f2(int a, int *b)
{
int c=0;
*b=3;
a=1;
c=a+*b+2;
return c;
}

int main()
{
int a=3,b=4,c=0;
c=f1(a,&b);
printf("\n a=%d, b=%d, c=%d \n", a,b,c);
c=f2(a,&b);
printf("\n a=%d, b=%d, c=%d \n", a,b,c);
return 0;
}
The function f2 works on a copy of a; it does not change the a in the main function.

Silly question... but how do I know if f2 works on a copy of a? And what about f1? Does having a in the brackets of f1 and f2, means they work on a copy of a?
If variable, (say "a" in this case) is defined in-scope it is local to that function.

1
2
3
4
5
6
void foo(int a)
{
// variable a is only handled in this function and does not affect calling inputs
}
//Somewhere else in code
foo(variable); // Does something but do not effect "variable" in calling function 


Simple way to change behavior so function effects passed arguments is to add &-symbol:
1
2
3
4
5
6
7
8
9
10
void foo(int &a)
{
// lets say:
a=1234;
//now variable used in call has changed
}
//.... now calling from somewhere else:
foo(some_variable_to_change); // does in fact change variable

//.. 
Last edited on
Topic archived. No new replies allowed.