Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between array and pointer [duplicate]

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..
like image 779
Normal People Scare Me Avatar asked Dec 08 '22 15:12

Normal People Scare Me


2 Answers

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.

like image 56
simonc Avatar answered Dec 11 '22 10:12

simonc


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.

like image 32
ZoomIn Avatar answered Dec 11 '22 10:12

ZoomIn