tags:

views:

107

answers:

5

I have the following function

void DoSomething(int start[10], int end[10])

When I call it via

void Do(void)
{
  int start[10] = {1,2,3,4,5,6,7,8,9,0};
  int end[10] = {1,2,3,4,5,6,7,8,9,0};
  DoSomething(start,end);
}

do I put two pointers (8 byte all together) or two arrays each of 40 bytes in size on the stack?

+7  A: 

In C, array arguments to a function are actually pointers, so you are putting two pointers on the stack, no copy of an array is made.

It would be the same as if the signature of DoSomething was:

void DoSomething(int *start, int *end);
Alex B
am I just confused, or are you correct except for the fact that in your case, DoSomething would be able to do pointer arithmetic, whereas in the question it wouldn't?
roe
Actually you can use pointer arithmetic on an array argument.
Alex B
+1  A: 

Arrays decay into pointers in C. You are putting the address of first elements of start and end on the stack.

Naveen
A: 

You put the array values in automatic storage ( usually on the stack ) in Do but only pass pointers to those arrays as arguments to DoSomething.

Whether the arguments are passed on the stack or as registers depends on your environment's ABI. If the architecture passes the arguments as registers and the call is inlined by the compiler and DoSomething doesn't need any variables, it may be that no stack is used by DoSomething. Conversely, some architectures always pass arguments on the stack and some compilers don't inline, in which case the stack will have the argument values as addresses of the arrays, as well as other state such as the return address.

Pete Kirkham
A: 

You are passing pointers to the called function.

void DoSomething(int start[10], int end[10]) {
    int x=0, k=10;
    while (k--) x += *(start++) * *(end++);
    if (x == 285) {
        /* OK: 1*1 + 2*2 + 3*3 + ... + 9*9 is 285 */
    }
}

void Do(void) {
    int start[10] = {1,2,3,4,5,6,7,8,9,0};
    int end[10] = {1,2,3,4,5,6,7,8,9,0};
    DoSomething(start, end);
}
pmg
+1  A: 

to pass arrays by value, place them in structs, that is (pseudocode):

struct int10 {
  int arr[ 10];
};

void DoSomething( struct int10 start, struct int10 end);

void Do(void) {
  struct int10 start;
  struct int10 end;
  ...
  DoSomething( start, end);
}
dmityugov