Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ pass char array to function and change it

Tags:

c++

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)

like image 532
Echo Avatar asked Aug 30 '13 12:08

Echo


People also ask

Can you pass char array to function in C?

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().

How do you pass the address of an array to a function in C?

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) .

What happens when an array is passed to a function in C?

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.

Can you reassign a char in C?

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.


1 Answers

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]);
}
like image 57
juanchopanza Avatar answered Sep 23 '22 18:09

juanchopanza