Possible duplicate:
Why does simple C code get a segmentation error?
Hey, everyone, I'm sure this is a very simple question, but apparently I don’t quite understand here.
I played with C many times over the winter break and just stumbled upon what I thought would work, but gives me a segmentation error.
if I declare the line as: char name [5] = "Mike"; I can manipulate the string: * (name + 1) = 'a'; This works great, the name becomes "Make."
If I declare: char * name = "Mike"; and then try the same thing: * (name + 1) = 'a'; I get a segmentation error. Why can't I do this?
If I malloc the space for the string: char * name = (char *) malloc (5 * sizeof (char)); and then copy the line for the name: strcpy (name, "Mike"); I can manipulate it as above just fine. * (name + 1) = 'a'; work.
What is the difference between char * name = "Mike" and char * name = (char *) malloc (5 * sizeof (char)); zbrc (name, "Mike") ;? Don't they both point to memory containing a string?
Sorry for the noobish question!
source
share