I haven't programmed in about 6 years and I started in a class where I picked up where we left off 6 years ago, needless to say I'm rusty, and didn't really do that well in the first place. I understand that * (e.g. int *value) is designating a pointer to value, and & (e.g. int &value) would give me the address in memory for that value, and -> designates the value to point to something else. But I am not sure when to implement each of these things for different functions when I am passing values and why. If someone could help me understand these concepts I would appreciate it very much so.
(These are just example functions, they aren't part of anything, I just don't see a difference between them except funcTwo would maybe set the address to 5?)
int funcOne ( int *value )
{
number = 5;
value = number;
return value;
}
int funcTwo ( int &value )
{
number = 5;
value = number;
return value;
}
int funcThree ( int value )
{
int number = 5;
number = number->value; //why not just have int *number; then set number = value;
return number;
}
There is only one function is syntactically correct if to assume that variable number is a global variable. it is funcTwo. The other two functions are invalid.:)
-> is used in referring to a member of an object via pointer.
1 2 3 4 5 6 7 8 9 10 11 12 13
struct Foo {
void bar ():
};
int main() {
Foo foo;
Foo * gaz = &foo; // store address of object foo in pointer gaz
Foo & qux = foo; // create a reference to object foo
foo.bar(); // call member function of object
gaz->bar(); // call same function of same object via the pointer
qux.bar(); // call same function of same object via the reference
return 0;
}
Your funcTwo takes a reference parameter. Reference is not same as address-of although both use the same symbol &.
Edit:
A pointer is a special type of variable that stores a memory address and has a dereferencing operator that allows accessing the value stored in the memory address.
1 2 3 4 5 6 7 8 9 10 11 12 13
void funcOne( int * value ) {
*value = 42; // write 42 to whereever the value points to
}
int main() {
int foo = 0;
// assert( 0 == foo );
funcOne( &foo );
// during the call of funcOne value holds the address of foo of main()
// funcOne will assign 42 into that memory location
// assert( 42 == foo );
return 0;
}
int funcOne ( int *value )
{
int number = 5;
*value = number;
return*value;
}
int funcTwo ( int &value )
{
int number = 5;
value = number;
return value;
}
int funcThree ( int value )
{
struct S { int value; } *number = new S;
number->value = value;
// some other stuff with number
value = number->value;
delete number;
return value;
}