ADT图DFS调试报错求助:C语言初学者代码问题咨询
Hey there! Let's break down the possible issues causing that error with your if(pg->visitInfo[visitV] == 0) line, especially since you're using an enum for vertex identifiers like A, B, C. Here are the most likely culprits to check:
1. Array Out-of-Bounds Access
This is the most common issue when using enums as array indices:
- Enums like
enum {A,B,C...}default to sequential values starting at 0, but you need to make sure yourvisitInfoarray's size matches the total number of vertices. For example, if your enum goes up toE(5 total vertices, values 0-4), but you declaredvisitInfoasint visitInfo[4];, accessingvisitInfo[E]will cross the array boundary and trigger a memory error. - Fix this by using the last enum value to define your array size, which ensures it always matches:
enum Vertex {A, B, C, D, E, VERTEX_COUNT}; // Add a count marker int visitInfo[VERTEX_COUNT] = {0}; // Array size matches vertex count - Also verify that
visitVnever gets assigned a value outside your enum's range—check if any logic in your code is accidentally setting it to an invalid number.
2. Null Pointer Dereference
If pg is a NULL pointer, accessing pg->visitInfo will immediately crash your program:
- Double-check that
pgis properly initialized beforeVisitVertex(pg, visitV)is called. In your main function, ensure&graphpoints to a valid, initializedALGraphinstance (not an uninitialized local variable). - Add a quick debug check to catch this early:
#include <assert.h> // ... assert(pg != NULL); // Will halt if pg is NULL, helping you spot the issue if(pg->visitInfo[visitV] == 0) { // Your code here }
3. Uninitialized visitInfo Array
If visitInfo isn't properly initialized, it may contain garbage values or point to invalid memory:
- Local arrays aren't automatically initialized to 0 in C—if
visitInfois a local variable, accessing its values before setting them can lead to undefined behavior. - Initialize the array properly either with an initializer list:
Or useint visitInfo[VERTEX_COUNT] = {0}; // All elements set to 0memsetto zero it out:#include <string.h> // ... memset(pg->visitInfo, 0, sizeof(pg->visitInfo));
4. Mismatched Enum Values and Array Indices
If you manually assigned values to your enum (e.g., enum {A=2, B, C...}), this can break the index-to-vertex mapping:
- Ensure your enum values are sequential starting at 0, or adjust your array size to account for the maximum enum value. For example, if
A=2and the highest value isE=6, your array needs to be at least size 7.
Quick Debug Tip
Print the value of visitV right before the problematic line to confirm it's within your enum's expected range. You can also inspect the address of pg and pg->visitInfo in your debugger to verify they point to valid memory.
内容的提问来源于stack exchange,提问作者Youngjun

