liorda
liorda

Reputation: 1572

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.

Upvotes: 0

Views: 196

Answers (3)

liorda
liorda

Reputation: 1572

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

Upvotes: 0

Praetorian
Praetorian

Reputation: 109189

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.

Upvotes: 1

jv42
jv42

Reputation: 8593

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.

Upvotes: 1

Related Questions