Difference between array and pointer

Yesterday I had a little problem with a makeshift "complex" function. Now it works, but I'm a little confused!

char* a = "Hello, World!"; //Works char b[] = "Hello, World!"; //Works also strcpy(a, "Hello!"); //Segmentation fault strcpy(b, "Haha!!"); //Works.. 

Where is the difference? Why does the char pointer cause a “segmentation error”?

Why does it work?

 char* a = "Haha"; //works a = "LOL"; //works.. 
+4
source share
2 answers
 char* a = "Hello, World!"; 

gives a pointer to a string literal. A string literal can exist in read-only memory, so its contents cannot be changed.

 char* a = "Haha"; //works a = "LOL"; //works.. 

changes the pointer a to point to another string literal. It does not try to modify the contents of the string literal, so it is safe / correct.

 char b[] = "Hello, World!" 

declares an array on the stack and initializes it with the contents of the string literal. The stack memory is written, so it is completely safe to change the contents of this memory.

+14
source

In the first example, when you try to write to the read-only memory indicated by a, you will get a segmentation error. If you want to use pointers, then allocate memory on the heap, use and delete it after using it. Where b is an array of characters initialized with "Hello, World!"

In the second example, the pointer points to another string literal, which must be exact.

+1
source

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


All Articles