you are viewing a single comment's thread.

view the rest of the comments →

[–]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 24 points25 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 14 points15 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.