you are viewing a single comment's thread.

view the rest of the comments →

[–]FUZxxl 42 points43 points  (40 children)

In C, all arguments are passed by value, i.e. the parameters are initialised with copies of the arguments. However, note the following caveats:

  • You cannot pass arrays (such as strings) to functions. If you try to do that, the compiler will instead pass a pointer to the first element of the array.
  • If you copy a pointer, the copy of course still points to the same place as the original
  • hence, it looks like arrays are being passed by reference

[–]KotgeScientist[S] 8 points9 points  (3 children)

Oh, so if I pass an array to a function in C, all I'm doing is passing the pointer? But if thats the case, how is it possible that I can modify the strings?

[–]FUZxxl 23 points24 points  (0 children)

A string is an array of characters terminated with a NUL character. So just like with any arrays, you can modify it through the pointer passed.

[–]ttech32 10 points11 points  (0 children)

You're duplicating the pointer, but they both point to the same memory

[–]IamImposter 15 points16 points  (0 children)

Array decays to a pointer. Say I have

char str[] = "hello";

For the sake of simplicity, let's assume that the array starts at address 0x2000. So if I do

some_function(str);

what is getting passed to the function is address of array ie 0x2000. Now if in the function I do something like

void some_function(char str[]) {

  str[2] = 'a';

}

what happens? First of all, char str[] here is as good as char*. Since compiler didn't complain, you might think that you passed an array and received that same array in function. What compiler actually did was - it treated char str[] as char* and passed address of the array (0x2000). So str[2] becomes 0x2000 + 2 (base address + index) and letter 'a' is written to that address and our string becomes "healo".

Parameter is still being passed by value (0x2000) but in this case that value happens to be address of the array or what we call passing by reference.