2. I see people pass a pointer by pointer...how does it work? are the changes done with pointer passed by pointer permanent? |
You have a structure:
1 2 3 4
|
struct MyStruct {
int a;
int b
};
|
You declare a structure:
MyStruct MyStructObject;
You have a pointer - no, no need.
you have a function, whether obj.function or only function - not interesting now.
1 2 3 4 5
|
void function( MyStruct * ptr)
{
ptr->a = 1;
ptr->b = 2;
};
|
And then you call such a function:
function( &MyStructObject);
Would the changes be permanent? |
Depends - how you understand "permanent".
I think, if you switch off your Commputer and the dada are not saved, it will not be permanent. And also your hard disc will only last some years - no it depends of the life time of your variable MyStructObject, whether this is a local or global variable.
-----------
If you pass by reference, you would write your function this way:
1 2 3 4 5
|
void function( MyStruct & ref)
{
ref.a = 1;
ref.b = 2;
};
|
And you would call your function this way: function( MyStructObject);
And what is the difference between pointer and reference? Some say much, some say not much.
We could say, pointer and reference are the same, only the compiler make them look differently. A reference is a pointer, which adress cou can't change and which the compiler let look like a variable. Could be some programmers couldn't unterstand pointers but understood variables - no that wasn't the only reason, the programmers can also not change the address, which means they cannot make so much nonsense. Oh maybe shouldn't have blabbed out the secret of the references. And now you know, what it means, when others say, you should take references - this he will understand and he cannot make much nonsense.
3. There's no need to pass by reference/pointer. |
Depends, how many data - on performance - on stack ressources. You could write your function as:
1 2 3 4 5 6
|
MyStruct function( MyStruct data)
{
data.a = 1;
data.b = 2;
return data;
};
|
And you could call your function so:
MyStructObject = function(MyStructObject);
This you could do and it makes not much difference for such a tiny structure object. But if it's a big structure object, you should consider, all the data are copied to the stack, when the function is called and all the data are copied to the stack, when the function returns and all the data are then copied to your structure object.
This means bad performance and a soon full stack. When you use a reference or pointer, there is only the address on the stack and you modify the data direct.