Paul the Pirate
Paul the Pirate

Reputation: 767

C string function calls, pass by value or reference?

I am having trouble figuring out what is going on, I thought C was pass by value but this simple function confuses me with how it works.

 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>

 void testFunc(char string1[])
 {
   char string2[50] = "the end";
   strcat(string1, string2);
   printf("in func %s \n", string1);
 }

 void main()
 {
    char string1[50] = "the start";
    printf("%IN MAIN %s \n", string1);
    testFunc(string1);
    printf("IN MAIN %s \n", string1);
 }

Confusingly the output is:

IN MAIN thestart

IN FUNC thestarttheend

IN MAIN thestarttheend

So what is going on here? Is C really passing the address of the char array instead of copying the value of it? I thought that is how char* would behave not char[]

Upvotes: 5

Views: 15050

Answers (4)

OldSchool
OldSchool

Reputation: 2183

In case of function parameter it is equivalent if you write:-

void testFunc(char string1[])

 {
   //body 
 }

or

void testFunc(char *string1)

 {
     //body
 }

in fact in C the first one is always converted to the second type of function defination.So in case of function parameter N element array of type T is converted into Array of type T,remember it and enjoy C programming.

NOTE this only happens in case of function parameters.

Upvotes: 1

nos
nos

Reputation: 229088

You can't pass a copy of an array to a function. When you use the name of an array, it evaluates to a pointer to the 1. element in the array (or as is commonly said, it decays to a pointer.). This happens everywhere except when using the array name in the sizeof and & operator.

So, you are passing in a pointer to the 1. element of the array to your testFunc()

 testFunc(string1);

is exactly the same as doing

 testFunc(&string1[0]);

Also, in a function argument list, char[] actually means char *

These 3 declarations are exactly the same

void testFunc(char *string1);
void testFunc(char string1[]);
void testFunc(char string[111]);

If you don't want to alter the passed in string, use something like:

e.g.

void testFunc(char string1[])
{  
  char string2[50]; 
  const char *end = "the end"; 
  strcpy(string2, string1); 
  strcat(string2, end);

(and be awake when using strcpy/strcat, it's easy to overflow arrays doing it like this)

Upvotes: 11

HelloWorld123456789
HelloWorld123456789

Reputation: 5359

It is passing by value.

string1 is the address of the starting position of the char array and this value is being passed.

And

void testFunc(char string1[])

is same as

void testFunc(char *string1)

Upvotes: 4

Thomas Padron-McCarthy
Thomas Padron-McCarthy

Reputation: 27632

C always passes arguments by value, but the string, like other arrays, is converted to a pointer to its first element, and then that pointer is passed. By value.

Upvotes: 6

Related Questions