Friday, July 31, 2009

Why do i need to derefence pointers when passing them to a function in the C languge?

Because a pointer is also a value that is perfectly legitimate to send into a function. Because you might be trying to actually send the pointer instead of the value that the pointer points to.





That would be called "pass by reference".


Example:





void PassByReferenceFunction( int * referenceToInt )


{


printf("I got %d!\n",*referenceToInt);


}





void main()


{


int value=10;


int * referenceToValue = %26amp;value;


PassByReferenceFunction( referenceToValue );


}





As you can see, we can pass the pointer into the function, and we can get the value by using the * operator before the pointer. This is very useful if we want the function to change the value of multiple parameters and have them stay changed when you return.





I imagine what you are doing is "pass by value".





Example:


void PassByValueFunction( int value )


{


printf("I got %d!\n", value);


}





void main()


{


int value=10;


int * referenceToValue = %26amp;value;





PassByValueFunction( *referenceToValue );


}





In this case, we are dereferencing the pointer outside of the function (in the function call) when we send "*referenceToValue" as the parameter to PassByValueFunction.





C (as opposed to C++) by default gives you a lot of leeway to mix and match types for your own purposes. It's very low level... it assumes you know what you are doing. Maybe you WANT the value of the pointer instead of what it points to. This is very powerful, especially when you are accessing hardware directly. Pointers are the most basic and powerful concept in C coding.

surveys

No comments:

Post a Comment