Why is my char * writable and sometimes read only in C ++

Recently, I have had big problems with understanding char*. Let's say I made a recursive function to return char*, but depending on how I initialize it, I get some access violations, and in my C ++ tutorial I did not find anything that would give me the correct way to understand therefore, I seek your help.

CASE 1 The first case when I received an access violation when trying to change the letters:

char * bob = "hello";

CASE 2 Then I tried this to make it work

char * bob = new char[5];
bob[0] = 'h';
bob[1] = 'e';
bob[2] = 'l';
bob[3] = 'l';
bob[4] = 'o';

CASE 3 But then, when I did cout, I got some random shit at the end, so I changed it to

char * bob = new char[6];
bob[0] = 'h';
bob[1] = 'e';
bob[2] = 'l';
bob[3] = 'l';
bob[4] = 'o';
bob[5] = '\0';

CASE 4 , ,

 char * bob = new char[6];
 bob = "hello\0";

CASE 5, , - , -

char* bob[];

- . , , , ?

+3
4

, ( /), . , , . , . , .

- , / , , .

char * bob = new char[6];
bob = "hello\0";

, . , :

char * bob = new char[6];
strcpy(bob,"hello");

strncpy(bob,"hello",6);

nul, "hello" , .

+11
char * bob = "hello"; 

:

const char __hello[] = "hello";
char * bob = (char*) __hello;

, , :

char * bob = "hello"; 
char * sam = "hello"; 

:

const char __hello[] = "hello";
char * bob = (char*) __hello;
char * sam = (char*) __hello;

, :

char * bob = new char[6];    
bob = "hello\0";

bob, . :

char * bob = new char[6];    
strcpy(bob, "hello");
+1

: ++ C, , ....

Ok. , ... new ++, C.

  • β„–1. char. ... , .
  • β„–2/β„–3. , nul terminator i.e. '\ 0'... , C/++, , ...
+-+-+-+-+-+--+
|H|e|l|l|o|\0|
+-+-+-+-+-+--+
            ^
            |
         Nul Terminator
  • β„–4 , strcpy , ​​ new, char *s = "foo";, . , char *s = new char[6]; strcpy(s, "hello");, s.

, , s, , , , , ... # 3 nul terminator... , , , 6, 5, nul-.

  • β„–5. char, .. , :
*(bob + 0) = "foo";
*(bob + 1) = "bar";

, , ... ...:) ...

+1

You should always use char const*for pointers to string literals (material in double quotes). Although the standard also allows it char*, it does not allow writing a string literal. GCC gives a compilation warning to assign a literal address to char*, but apparently, some other compilers do not.

+1
source

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


All Articles