开发者

Passing arrays to functions by their names in C

I'm declaring a global variable in my program:

double mat[3200][3200开发者_开发百科];

when passing this array to fwrite() by using the variable's name as argument, I get stack overflow thrown at runtime.

fwrite(mat, sizeof(double), 3200*3200, fid);

Why is that? Shouldn't the compiler replace the variable mat with a pointer to its first element?

I've read here and here, and still can't understand.


A stack overflow error could be due to either an infinite recursion (unlikely in your example) or too much data passed on the stack (parameters). It seems your array is passed by copy, not by adress.

You can try to replace the call by

fwrite(&(mat[0][0]), sizeof(double), 3200*3200, fid);

A static array is not a pointer.


Is the array being created on the stack? For instance, are you creating the array like this?

void foo()
{ 
  double mat[3200][3200];

  // ... other stuff

  fwrite(mat, sizeof(double), 3200*3200, fid);
}

If so, are you sure that it is fwrite and not the array declaration itself that is causing the stack overflow? The array occupies 3200*3200*8 = 81920000 bytes (about 78 MiB), probably a little too big for a stack allocation. Try malloc'ing the array instead.


I guess that the variable was passed (using the stack) by value. Thanks anyone for trying to help me figure this out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜