You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言函数内访问指针数组崩溃:原因分析与解决方法

Why Your Program Crashes & How to Fix It

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 test to the function, the array name decays to a pointer to its first element. For your 2D array, that first element is test[0]—a 1D array of 1024 char*s. So test becomes a pointer of type char* (*)[1024] (a pointer to an array of 1024 char*s).
  • Your function treats this pointer as a char** (a pointer to a single char*). When you try to access transactions[0], the code tries to interpret the value of that char* (*)[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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:41:15