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; array is of type const char* , not char* .In order to write a C++ pointer to a string, you need:
#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"}; } array is a constant string. - LLENN pmwarning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings] - LLENNwarning 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. - KomdoshSource: https://ru.stackoverflow.com/questions/819801/
All Articles