When I wrote the code in the afternoon, I encountered a bug and found it after a while. First, paste the source code containing the bug. The highlighted bug is:
Void CreateGraph (MGraph * G)
{
Printf ("Enter the graph type. 1 indicates a directed graph, and 0 indicates an undirected graph. ");
Scanf ("% d", & G-> graphkind );
If (G-> graphkind = 1)
{
Printf ("build directed graph now. ");
CreateDG (& G );
} // Construct a directed graph. Here, you should not use an address character.
Else if (G-> graphkind = 0)
{
Printf ("now build an undirected graph. ");
CreateUDG (& G );
} // Construct an undirected graph. Here, you should not use an address character.
Else
{Printf ("Wrong! ");
Exit (0 );}
}
}
Void CreateUDG (MGraph * G) // constructs an undirected graph.
{
Several lines of code are omitted here ......
}
Void main ()
{
MGraph graph1;
CreateGraph (& graph1 );
}
Bug Analysis:
From the code above, we can see that I have written two functions using pointer-type parameters. The second CreateUDG function is called by the first function CreateGraph nested.
Generally, when we call a function of a pointer parameter, we write it like this:
Void funA (int *)
{
........
}
Int argue1;
FunA (& argue1 );
We pass the address of argue1 to funA, so that the value of argue1 is changed accordingly after the data pointed to by address a is modified in funA (if it is not a pointer parameter, then, the value of argue1 is not changed outside the function. All that changes is the local variable a of the function ). We use the & argue1 to get the address of argue1 during the call.
However, when nested functions and nested functions use pointer type, a bug occurs. In the above error code segment, in the main function, we call CreateGraph (& graph1) and have passed the address of graph1 to the CreateGraph function, therefore, in this function, G represents the address of graph1. Therefore, when CreateGraph is nested to call CreateDG, the parameter does not need to be retrieved again, because G itself is an address, the address is meaningless.
Therefore, when writing pointer-type parameters, especially nested calling, it is necessary to analyze what the real parameters are passed in. Do not write them properly and it is hard to write them.
It is worth mentioning that, in this bug, the VC6.0 compiler will not report an error, but it will give a warning. In this way, the program can be executed, but the returned result is not what you want... To put it bluntly, if another programmer tells you to write a program later, you can ignore the error. You have to think twice, otherwise, you may just look for bugs as though I did.