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?
There’s a crucial point to make here, everything is really passed by value for example, this will pass a copy of
atofoo()(which happens to be a pointer to some memory):That’s why if you do something like this in
foo()it doesn’t really change the pointerainmain()but changes the local copy:In other words, you can use
foo()‘s local copy ofato change the memory pointed to by ‘a’ but not to change whatapoints to inmain().Now, to pass something “by reference” you pass a copy of a pointer-to-pointer to the function (something like a->b->memory):
So when you assign to it in
foo()to changes the pointer inmain():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:
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
ais allocated on the heap, the memory ofbhowever, 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
constand you should not attempt to modify it anywhere but you can change the second one: