Difference between array and pointer [duplicate]

2020-03-24 06:15发布

问题:

Yesterday I had a little trouble with a homemade "strcpy" function. It works now though 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 fault"?

Why does this even work? :

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

回答1:

char* a = "Hello, World!";

gives you a pointer to a string literal. A string literal may 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 a different string literal. It doesn't attempt to modify the contents of either string literal so is safe/correct.

char b[] = "Hello, World!"

declares an array on the stack and initialises it with the contents of a string literal. Stack memory is writeable so its perfectly safe to change the contents of this memory.



回答2:

In your first example since you are trying to write to a read only memory pointed by a,you will get the segmentation fault.If you want to use pointers then allocate the memory on heap,use and delete it after its use. Where as b is an array of chars initialized with "Hello, World!".

In the second example you are making the pointer to point to different string literal which should be fine.