1

I have the following code:

#include <stdio.h>

void changeValue(char str[]) {
        str[2] = 'a';
}

int main()
{
  char a[]="Hello world";
  changeValue(a);
  printf("%s", a);
}

And I am trying to understand how this is working. Why when passing the array named 'a' it is being passed by reference? So, the changes that I do inside changeValue are actually seen from the outside? Shouldn't be the function parameter defined as char *str, in order to be able to change it?

StarTrek18
  • 323
  • 4
  • 15

3 Answers3

5

In many situations (including passing them as function arguments) arrays are converted to a pointer to their first element.

So, what you are passing is not an array. In fact, the syntax used in the prototype is just eye candy

void changeValue(char str[]);
void changeValue(char *str);

the above prototypes are identical!

pmg
  • 106,608
  • 13
  • 126
  • 198
3

C has no notion of "pass by reference". Everything is passed by value. When you pass an array to a function it decays to a pointer to the first element.

Even though the signature of changeValue appears to take a char[] as its argument, it actually receives a char*.

Ed S.
  • 122,712
  • 22
  • 185
  • 265
2

You were right before doubts corroded your confidence in the standard: In C only passing by value is possible.

So, why do you seem to see pass by reference?

Simply explained, there are only two contexts in which an array does not immediately decay to a pointer to its first element: sizeofand address (&).

Now, however often you copy this pointer, it will still point to the same memory block. For that reason, whenever it looks like a function receives an array, it actually receives a pointer.

void changeValue(char str[]);
void changeValue(char *str);
/* These two above are equivalent. */
void changeValue(char str[static 1]);
/* the one above always points to at least one element (C99) */
Deduplicator
  • 44,692
  • 7
  • 66
  • 118