C语言:使用指针访问二维数组失败,一维正常,求解决方法
Hey there! Let's figure out why your code isn't working with the 2D array pointer, and fix it step by step.
The Core Problem: Mismatched Pointer Types
Your line char *temp = &test; is the culprit here. Let's break down the types:
testis a 2D array of typechar[2][4](2 rows, each with 4 chars).&testgives you a pointer to this entire 2D array, which has the typechar (*)[2][4](read as "pointer to an array of 2 arrays of 4 chars").- You're trying to assign this to a
char*variable—these types are completely incompatible! When you dotemp[1][2], the pointer arithmetic gets messed up because the compiler expects achar*to jump 1 byte per index, but your actual pointer points to a much larger structure.
In 1D arrays, you might have gotten away with temp = &test (though it's still technically incorrect), because the array name decays to a pointer to its first element, and the memory layout is linear. But 2D arrays add an extra layer of indirection that breaks this hack.
Fixes to Make It Work
Here are two clean, correct ways to handle this:
1. Use the Exact Pointer Type for the 2D Array
Declare temp as a pointer to your 2D array type, then dereference it to access the array elements:
#include <stdio.h> int main() { char test[2][4] = {"BbBa","CBAD"} ; char ch = 'A'; char (*temp)[2][4] = &test; // Correct pointer type int i=0; if ((*temp)[1][2] == ch){ // Dereference temp first to get the array printf("Yes"); } else{ printf("No."); } getchar(); return 0; }
2. Use a Pointer to the Rows of the 2D Array
A 2D array can decay to a pointer to its first row (which is a char[4] array). So you can declare temp as a pointer to a 4-char array, which lets you use temp[row][col] directly:
#include <stdio.h> int main() { char test[2][4] = {"BbBa","CBAD"} ; char ch = 'A'; char (*temp)[4] = test; // Pointer to each 4-char row int i=0; if (temp[1][2] == ch){ // Now this works as expected! printf("Yes"); } else{ printf("No."); } getchar(); return 0; }
This is probably the more common approach because it lets you use the familiar [row][col] syntax without extra dereferencing.
Why This Works
In the second fix, temp points to the first row of test. temp[1] jumps to the second row (since each row is 4 chars, it moves 4 bytes in memory), and temp[1][2] grabs the third character of that row—which is exactly 'A', so your code will print "Yes" as expected.
内容的提问来源于stack exchange,提问作者Cc Li

