在C语言(Code::Blocks)中使用数组访问矩阵位置的问题求助
Hey there, let's break down why your mat[vet[a]][vet[a+1]] line is causing a crash and walk through fixes for the most common issues:
1. You're accessing out-of-bounds indices in the matrix
Matrix indices in C start at 0, so valid row indices are 0 to LINES-1, and valid column indices are 0 to COLUMNS-1. If the values stored in vet[a] or vet[a+1] fall outside these ranges, you'll be accessing memory that doesn't belong to mat—which almost always causes a crash.
Fix: Add bounds checking before accessing the matrix:
// Check if both indices are within valid ranges if (vet[a] >= 0 && vet[a] < LINES && vet[a+1] >= 0 && vet[a+1] < COLUMNS) { int value = mat[vet[a]][vet[a+1]]; // Use the value here } else { printf("Error: Invalid index pair vet[%d]=%d, vet[%d]=%d\n", a, vet[a], a+1, vet[a+1]); }
2. You're going out of bounds in the vet array itself
Your vet array has 20 elements (indices 0 to 19). If a is set to 19, a+1 becomes 20—which is beyond the last valid index of vet. Accessing vet[20] reads unallocated memory, leading to a crash.
Fix: Ensure a is always at least 0 and at most 18. If you're iterating through pairs of indices in vet, use a loop with a step of 2:
// Iterate over vet in pairs (row, column) for (int a = 0; a < 20; a += 2) { // Now a+1 will never exceed 19 if (vet[a] >= 0 && vet[a] < LINES && vet[a+1] >= 0 && vet[a+1] < COLUMNS) { int value = mat[vet[a]][vet[a+1]]; // Process the value } }
3. The vet array contains uninitialized garbage values
If vet is a local array (declared inside a function without initialization), its elements will hold random garbage values. Using these as indices will almost certainly point to invalid memory locations.
Fix: Make sure you properly initialize vet with valid row and column indices before using it. For example:
// Initialize vet with valid index pairs vet[0] = 0; vet[1] = 1; // Access mat[0][1] vet[2] = 2; vet[3] = 0; // Access mat[2][0] // ... fill the rest of vet with valid pairs
4. The mat matrix isn't properly defined or allocated
Double-check that your mat matrix is declared correctly. For example, if you defined LINES as 5 but declared mat[4][COLUMNS], that's a mismatch that will cause out-of-bounds accesses. If mat is dynamically allocated, ensure the allocation succeeded and matches your LINES/COLUMNS values.
Fix: Verify your matrix declaration matches your macro definitions:
#define LINES 5 #define COLUMNS 5 // Correct declaration int mat[LINES][COLUMNS];
内容的提问来源于stack exchange,提问作者Alexandre Mendes

