匈牙利算法程序开发:二维结构体指针数组内存访问异常求助
Hey Chris, sorry to hear you're stuck on this memory access violation while setting up your cost matrix for the Hungarian Algorithm. Let's walk through the most common culprits and fixes for this issue—these are the things I'd check first if I was debugging your code:
1. Verify Complete Memory Allocation for Your 2D Pointer Array
A super common mistake with 2D pointer arrays is forgetting to allocate memory for the inner array elements. If you only allocate the outer array of pointers but don't initialize each pointer to point to a valid array of your custom class objects, accessing matrix[i][j] will hit an unassigned memory address.
Here's what proper allocation should look like (assuming your class is named WorkerJob):
// Define your class with a safe constructor class WorkerJob { public: int cost; // Initialize cost to avoid garbage values WorkerJob() : cost(0) {} }; int numWorkers = 5; // Replace with your actual count int numJobs = 5; // Replace with your actual count // Step 1: Allocate the outer array of pointers WorkerJob** costMatrix = new WorkerJob*[numWorkers]; // Step 2: Allocate inner arrays for each worker for (int i = 0; i < numWorkers; ++i) { costMatrix[i] = new WorkerJob[numJobs]; }
Without that second loop, each costMatrix[i] is a wild pointer—writing to it will trigger a memory access violation.
2. Check for Index Out-of-Bounds Errors
Double-check that your loops for loading cost values aren't exceeding the bounds of your array. For example, if you have 4 workers and 4 jobs, your loops should run from 0 to 3 (not 1 to 4). Off-by-one errors are easy to miss and will cause you to access memory outside the allocated array space.
3. Ensure Your Custom Class Is Properly Initialized
If your class has uninitialized member variables (especially pointers), or if its constructor doesn't set up necessary state, accessing those members could lead to invalid memory access. Make sure your class's constructor initializes all relevant fields (like the cost value you're trying to set) to valid values.
4. Use a Debugger to Pinpoint the Exact Error
Take advantage of your IDE's debugger (like Visual Studio's Debugger or GDB) to break on the memory access violation. When the error triggers, check the values of your indices (i and j) and the state of your costMatrix pointer—this will tell you exactly whether you're dealing with a wild pointer, an out-of-bounds index, or an uninitialized class member.
Once you've confirmed your memory is properly allocated and indices are valid, you should be able to safely load your cost values into the matrix without hitting the violation.
内容的提问来源于stack exchange,提问作者Chris

