I try to make a function that can change the content of a specified char array
void change_array(char *target)
{
target="hi";
}
int main()
{
char *a[2];
change_array(a[1]);
cout<<*(a[1]);
}
But then the content of a[1] stays at 0x0(void)
A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array's name. In C, when we pass an array to a function say fun(), it is always treated as a pointer by fun().
To explicitly state this: Its is not possible to "pass an array" in C. All one can do is pass the address of its 1st element by just doing me(x) (where the array x decays the address of its 1st element) or pass the array's address by doing me(&x) .
The address of the first variable is passed when you pass an array to a function in C. An array passed to a function decays into a pointer to its first element.
Answers. After the initial assignment, to reassign C style string you have to copy the characters to the array one element at a time. The thing to remember about this type of string is that it isn't a special type, it is literally just an array of characters.
First, your function has a copy of the pointer passed to it, so there is no effect seen on the caller side. If you want to modify the function argument, pass a reference:
void change_array(char*& target) { ... }
// ^
Second, you cannot/should not bind a non-const pointer to a string literal. Use const char*
instead.
void change_array(const char*& target) { ... }
// ^^^^^ ^
int main()
{
const char* a[2];
change_array(a[1]);
cout<<*(a[1]);
}
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