Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array are passed by value or by reference?

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?

like image 545
AR89 Avatar asked Nov 19 '12 07:11

AR89


1 Answers

There's a crucial point to make here, everything is really passed by value for example, this will pass a copy of a to foo() (which happens to be a pointer to some memory):

int *a = malloc(20);
foo(a);

That's why if you do something like this in foo() it doesn't really change the pointer a in main() but changes the local copy:

foo(int *a)
{
  a = NULL; /*changes local copy of the pointer*/
}

In other words, you can use foo()'s local copy of a to change the memory pointed to by 'a' but not to change what a points to in main().

Now, to pass something "by reference" you pass a copy of a pointer-to-pointer to the function (something like a->b->memory):

int *a = malloc(20);
foo(&a);

So when you assign to it in foo() to changes the pointer in main():

foo(int **a)
{
  *a = NULL; /*changes the pointer in main */
}

Now to answer some of your other questions, when you use an array name it is converted to a pointer to the first element of the array:

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

The last two function calls are equivalent in that they both pass a pointer to the first element of some memory, the difference is the memory for a is allocated on the heap, the memory of b however, is allocated on the stack.

Finally, strings, the following are similar, in that the same principle applies, however the first one is a constant string literal and should be defined as const and you should not attempt to modify it anywhere but you can change the second one:

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

 

like image 126
iabdalkader Avatar answered Oct 05 '22 02:10

iabdalkader