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[]
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With