C语言函数内访问指针数组崩溃:原因分析与解决方法
Let's break down exactly what's causing the crash and walk through the fixes step by step.
The Core Issue: Type Mismatch
You've defined a 2D array of char* pointers:
char* test[3][1024] = {"Trans1", "Trans2", "Trans3"};
But your function expects a 1D array of char* pointers (which in C decays to a char** pointer):
extern BLOCK* creerBlock(char* transactions[], int nbTransactions, char *pHashCodePrec, int numBloc);
Here's why this mismatch crashes your program:
- When you pass
testto the function, the array name decays to a pointer to its first element. For your 2D array, that first element istest[0]—a 1D array of 1024char*s. Sotestbecomes a pointer of typechar* (*)[1024](a pointer to an array of 1024char*s). - Your function treats this pointer as a
char**(a pointer to a singlechar*). When you try to accesstransactions[0], the code tries to interpret the value of thatchar* (*)[1024]pointer as a string address. That's an invalid memory location, hence the crash.
Also, note your initialization: {"Trans1","Trans2","Trans3"} only sets test[0][0], test[1][0], and test[2][0] to the string literals—all other elements in the 2D array are automatically initialized to NULL.
Fixes to Correctly Access the Values
Option 1: Update the Function to Match Your 2D Array
Modify the function declaration to accept a 2D array of char*s. Since your second dimension is fixed at 1024, you can write:
extern BLOCK* creerBlock(char* transactions[][1024], int nbTransactions, char *pHashCodePrec, int numBloc);
If you're using C99 or later (which supports variable-length arrays), you can make it more flexible by passing dimensions first:
extern BLOCK* creerBlock(int nbTransactions, int numCols, char* transactions[nbTransactions][numCols], char *pHashCodePrec, int numBloc);
Inside the function, access your strings (stored in the first position of each row) like this:
printf("%s", transactions[i][0]); // Prints "Trans1" when i=0, etc.
Option 2: Use a 1D Array to Match the Existing Function
If you don't want to change the function, redefine your test array as a 1D array of char*s (which matches what the function expects):
char* test[3] = {"Trans1", "Trans2", "Trans3"};
Call the function as before:
creerBlock(test, 3, NULL, 1);
Now inside the function, you can safely access the strings with:
printf("%s", transactions[0]); // Prints "Trans1" printf("%s", transactions[1]); // Prints "Trans2"
内容的提问来源于stack exchange,提问作者Antarès Be

