简体   繁体   中英

What's the difference between defining a string as an array or as a char pointer?

When I execute the code below,

#include <stdio.h>
#include <string.h>
int main ( ){
    char string [] = "Home Sweet Home";
    printf ("%s",(char*)memmove(string,&string[5],10));
    }

the output is "Sweet Home Home".

But; when I change the code like below,

#include <stdio.h>
#include <string.h>

int main ( )
{
    char* string = "Home Sweet Home";
    printf ("%s",(char*)memmove(string,&string[5],10));

}

it gives segmentation fault.

What changes when I define this array as a char pointer?

What changes when I define this array as a char pointer?

In this case the most importantly: the mutability of the data changes.

char string [] = "Home Sweet Home";

The "Home Sweet Home" here is an initializer for array string . It initializes the string with the characters with zero terminating character. The array size is inferred from the initializer, (if I count right) that's 16 characters. Array string is declared as char , so it mutable and you can change it.

char* string = "Home Sweet Home";

The "Home Sweet Home" here is a string literal . String literals are immutable, not modifiable, cannot be modified. A pointer to the string literal is stored in string pointer. Modifying a string literal results in undefined behavior. Segmentation fault is the error, when a program accesses a memory location that it is not allowed to access. In this case the program tries to write to a memory location that it is not allowed to modify.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM