Alex Rivera | Logout

Array are passed by value or by reference?

Asked 2012-11-19T07:24:15.577
13

I know for sure that

function(int *a); function(int a[]);

in C are the same, function(int a[]) will be translated into function(int *a)

int *a = malloc(20);
int b[] = {1,2,3,4,5};

These two are not the same, the first is a pointer, the second is an array. What happens when I call function(b)?(function(int *a)) I know that b is on the stack, so how is passed to that function?

Secondly, strings:

char *c1 = "string";
char c2 [] = "string";

In this case I don't know where is c1, and I suppose that c2 is on the stack. Suppose that function now is: function(char *c), which is the same as function(char c[]), what happens when I call function(c1), and function(c2), the strings will be passed by reference or value?

Edit
Report

1 Answer

7

From K&R2

When an array name is passed to a function, what is passed is the 
location of the initial element. Within the called function, this 
argument is a local variable, and so an array name parameter is a 
pointer, that is, a variable containing an address.

The argument declaration char c2 [] is just syntactic sugar for char* c2.

Everything in C gets passed as value. For further explanation of this use this link.

Also Eli Bendersky has an excellent article discussing the same.

answered 2012-11-19T07:36:40.050

Your Answer