The difference between using pointers and references for function input parameters.
Recently I made a tool and needed to assign a value to a global variable during function rectification.
RadixNode * g_pstRootBase
The source of the assignment is the defined struct: trSet-> tNameSet [I]. tName address in TreeSet treeSet TreeSet = {0} (where I is a variable.
The following is the definition of the trSet struct:
Typedef struct tagTreeName
{
RadixNode * tName;
Char * fName;
} TreeName;
Typedef struct tagTreeSet
{
TreeName tNameSet [MAX_SYMBOL_TREE_NUM];
Int realNum;
} TreeSet;
For other processing needs, a function is written, and its prototype is:
Int setTreeName (TreeSet * trSet, RadixNode ** tName)
You want to assign the trSet-> tNameSet [I]. tName address to g_pstRootBase through the second input parameter tName (the function has been deleted)
Parameter passing method: setTreeName (& trSet, & g_pstRootBase). internal processing is as follows:
Int setTreeName (TreeSet * trSet, RadixNode ** tName)
{
TName = & trSet-> tNameSet [I]. tName;
}
}
However, during debugging, it was found that g_pstRootBase was not successfully assigned a value, that is, g_pstRootBase is still the initial value.
After analysis, we can find that & g_pstRootBase indicates the g_pstRootBase address. It is not a real pointer variable, but an address constant!
Modify the assignment of g_pstRootBase in the function as follows:
Int setTreeName (TreeSet * trSet, RadixNode ** tName)
{
* TName = (RadixNode *) (& trSet-> tNameSet [I]. tName );
}
}
In this way, the program runs normally, and the address of & trSet-> tNameSet [I]. tName is assigned to the address * tName.
We can conclude from the above: Use reference as the left value as little as possible. If you need to assign values through function parameters (out parameters), it is best to use a temporary pointer variable to get the address, and then assign values to the required variables.