Difference between array and pointer [duplicate]

做~自己de王妃 提交于 2019-12-01 06:21:00
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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!