I have this code. There is a function

void chchar(char* ch){ ch = "asfafgag"; } 

Why after executing such a code, array is not equal to "asfafgag"?

 char* array = "abc"; chchar(array); cout << array; 

    2 answers 2

    1. Your variable array is of type const char* , not char* .
    2. Because there is an implicit copying of the transferred data.

    In order to write a C++ pointer to a string, you need:

    1. Allocate memory from the heap.
    2. Pass the pointer by reference, or pass the pointer to the pointer, "dereference" the pointer, and write data to it.

     #include <iostream> #include <cstring> #include <stdlib.h> using namespace std; void chchar(char** str) { strcpy(*str, "String data from `chchar`"); } int main(int argc, char** argv) { char* data = static_cast<char*>(malloc(sizeof(100))); strcpy(data, "Blablbla"); printf("Data before call `chchar`: %s\n", data); chchar(&data); printf("Data after call `chchar`: %s\n", data); free(data); system("pause"); } 

    You can also pass a pointer to a string by reference:

     #include <iostream> #include <cstring> #include <stdlib.h> using namespace std; void chchar(char*& str) { strcpy(str, "String data from `chchar`"); } int main(int argc, char** argv) { char* data = static_cast<char*>(malloc(sizeof(100))); strcpy(data, "Blablbla"); printf("Data before call `chchar`: %s\n", data); chchar(data); printf("Data after call `chchar`: %s\n", data); free(data); system("pause"); } 

    The result of both cases:

     Data before call `chchar`: Blablbla Data before call `chchar`: String data from `chchar` 

    Example: https://ideone.com/1W85dS

      In the function, you change the value of a pointer to a string, thus you do not change the external pointer variable, but change the pointer address, in the end it turns out that you just changed the address of a local variable.

      To bring the change out, you need a pointer to a pointer, and change it.

       void chchar(char** a); int main() { char* array [] = {"sdf"}; chchar(array ); std::cout << "Hello, " << *array << "!\n"; } void chchar(char** a){ *a = {"asfafgag"}; } 
      • Your array is a constant string. - LLENN pm
      • No, this array is a pointer to a string pointer, and in the function we change the pointer address. - Komdosh
      • warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings] - LLENN
      • AND? Well, yes, the warning case says, you really shouldn't use pointers to lines in the pluses and there are still a lot of comments you can bring, but it is compiled and works. - Komdosh
      • And I can specifically write this variant char * array = "abc"; change through function? - breeze