Write permission for char *

Compatible question: you need to be able to modify the contents of char * in C ++.

I have a function that is something like this: char * buffer = (char *) FUNCTION

Now I need to change the "buffer", for example. do something like this buffer [1] = "h";

Among what I tried, the following: char * string = "Hello World"; buffer char [65]; // I still need to know the exact size of strcpy (buffer, string); buffer [1] = "r";

I also tried with malloc. Unfortunately, the compiler always complains about the following: "it is not possible to convert from const char [2] to char". This happens in the windows. I have no such problem with g ++ compiler.

I looked through the following links, but still I can not do anything. http://www.developerweb.net/forum/archive/index.php/t-3517.html About character pointers in C Is it possible to change the char string in C?

thank

+3
source share
4 answers

Since your question is tagged with C ++, I have to question your intentions to use raw char * s, it is not recommended if you are not sure.

-, a char * char [] . , const char * "Hello World", . . "r" - , const char *. , const char * char, . "r", char.

:

std::string mystring((char*)FUNCTION); // assume that FUNCTION
                                       // will free it own memory.
if (index < mystring.size())
    mystring[index] = 'r';
// mystring now cleans up it own memory in all cases.
+5

* char string = "Hello World", " ", char string [] =.., :

    char * strReadOnly = "read-only-data";
    //strReadOnly [3] = '0'; //access violation 
    char stReadWrite [] = "read-write-data";
    stReadWrite [3] = '0'; // Ok, but just make sure that indexes are in range

, , :

 char * src = "read-only-data";
 const int len = strlen(src);
 char * dst = new char[len+1];
 strcpy(dst, src); 
 dst[3] = '0'; // ok to change

 delete [] dst; // don't forget to delete dst
+4

, '', char , "" ( char), char [2] (char + null) char.


*(buffer + x) = 'h';

x - char .

+3

, :

char  myArray[] = "Hello Mars!";
char* myPointer = "Hello World!";

, . .

char ( C ). . , const. :

( hdd), . myPointer. (, , ). -, , . , . . :

++ ?

:

char*, , . . . , :

myPointer = myArray;

myPointer const, , myArray . . myPointer , "Hello Mars!". :

myPointer[3] = 'Z';

, , .

constness

, .

const char* const myPointer2 = myPointer;

const const, myPointer2 , const const, - myPointer2 = myArray;

. .

+2

Source: https://habr.com/ru/post/1751538/


All Articles