Manipulating strings in a C question

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!

+3
source share
4 answers

char name[5] = "Mike" "Mike". char* name = "Mike" "" . "" , , .

+10

, , .

char array[5] = "Mike"

"Mike", 5 (... , , )

char *array = "Mike"

"Mike", .

" " , , .

+2

, Undefined Behavior

char *array="Mike"; /* String Literal is stored in read only section of memory */

*array='P'; /* Undefined Behavior */

C99 6.4.5.6 ( - ) :

, , . , .

 char array[5] = "Mike";/*Creates a local array and copies the string "Mike" into it*/

 *array='P';/*Fine*/
+2

, , .

malloc(), , .

When you do something in the middle that fails, you pointed to a line that lives in memory that you are not allowed to change. It is static and read-only.

+1
source

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


All Articles