C 将3D数组传递给函数。

C 将3D数组传递给函数。,c,character-arrays,C,Character Arrays,我很难将3D数组传递给函数。我已经在谷歌上搜索到了死亡,我想我理解了,但是代码在运行时崩溃了,没有输出。(代码块,gcc) #包括 #包括 void foo(char(*foo_数组_in_foo)[256][256]); int main() { char foo_数组[256][256][256]; int line_num=0; printf(“你好,世界!\n”); foo(foo_数组); 返回0; } void foo(char(*foo\u数组\u in\u foo)[256][2

我很难将3D数组传递给函数。我已经在谷歌上搜索到了死亡,我想我理解了,但是代码在运行时崩溃了,没有输出。(代码块,gcc)

#包括
#包括
void foo(char(*foo_数组_in_foo)[256][256]);
int main()
{
char foo_数组[256][256][256];
int line_num=0;
printf(“你好,世界!\n”);
foo(foo_数组);
返回0;
}
void foo(char(*foo\u数组\u in\u foo)[256][256])
{
printf(“在foo\n中”);
}

堆栈溢出

256*256*256 = 16777216 bytes > STACK_SIZE
这就是分段错误的原因


如果您需要如此大的内存量,则必须使用
malloc

问题在于
main

char foo_array[256][256][256];
这将创建一个16777216字节的局部变量,使堆栈溢出。您可以通过声明数组
static

static char foo_array[256][256][256];
或者使用
malloc

char (*foo_array)[256][256] = malloc( 256 * 256 * 256 );
if ( foo_array == NULL )
    exit( 1 );      // if malloc fails, panic
如果选择
malloc
,请记住在使用完内存后释放内存


注:
foo
函数的声明没有问题。

你能解释一下
malloc
吗?@iharob带有1D数组
char bar[100]
变成
char*bar=malloc(100)
。使用2D数组时,
char blah[4][5]
变为
char(*blah)[5]=malloc(4*5)
。我的回答显示了如何声明指向3D数组的指针以及它的malloc内存。还有一个问题,为什么有些人在
malloc
失败时使用
exit
?我想主要是微软的windows程序员,但我不明白,如果失败了,你可以重试,或者做一些事情,比如通知用户并清理其他资源,我知道这些资源很可能会被操作系统清理掉。但是使用
exit
@iharob背后的逻辑是什么?关键点是应该始终检查
malloc
的返回值,并且需要处理
NULL
的返回值。调用
exit(1)
是证明这一点最简单的方法。我仍然认为应该是
char(*foo_array)[256][256]=malloc(256*sizeof(char*))
我可能错了。这对帮助来说是有意义的。
char (*foo_array)[256][256] = malloc( 256 * 256 * 256 );
if ( foo_array == NULL )
    exit( 1 );      // if malloc fails, panic