Strings are interpreted as pointers when you pass them to a function in C, for example func(str)
will pass a pointer to the block of memory named str. So by default, strings are already pointers when passing them into a function. Is there a way to pass a string by value where you don't have to end up manipulating the contents of str
?
CodePudding user response:
First, what is a string? It's an array of characters and then a \0
. Just to make sure we all agree on that.
So the question is, can you pass an array of characters by value? And the answer is yes, but only if it's inside a struct or union:
struct String40Chars {
char str[41];
};
void f(struct String40Chars s) {
// s was passed by value - including s.str
}
However, you can't pass an array directly due to a historical quirk:
void f(char str[41]) {
// you would think this would work,
// but actually, the compiler converts it to void f(char *str)
}
That is unfortunate for people who really do want to pass arrays by value.
Luckily you usually don't need to. In every case I can think of, a pointer is good enough, and faster as well since it doesn't need to copy the array. Maybe you can elaborate on why you need to pass an array by value.
P.S. You talk about "strings being pointers" but that is nonsense. Strings are arrays. You can have pointers to arrays but the pointer is not the array.
CodePudding user response:
The only way to achieve value semantics with string arguments in C is to have a struct or union that wraps the string.
Something like:
#define STR_BY_VALUE_MAX_LENGTH 128
typedef struct StrByValue_
{
char str[STR_BY_VALUE_MAX_LENGTH];
} StrByValue;
void f(StrByValue strByVal)
{
// Changes to strByVal will not affect the caller
}
Of course the caller will have to initialize the StrByValue
object by copying the string (e.g. using strcpy) into the str
field. You can also add a len
field to the StrByValue
struct if you don't want to use zero terminated strings.