Skip to main content

CASE 1:

char *str = "Hello";
str[0] = 'M'  //NoWarning warningmay orbe errorissued by compiler, justand Undefinedwill Behaviorcause segmentation fault upon running the programme

The above sets str to point to the literal value "Hello" which is hard-coded in the program's binary image, which is flagged as read-only in memory, means any change in this String literal is illegal and that would throw segmentation faults.

CASE 2:

const char *str = "Hello";
str[0] = 'M'  //Compiler issuesCompile atime warningerror

CASE 3:

char str[] = "Hello";
str[0] = 'M'; // legal and change the str = "Mello".

CASE 1:

char *str = "Hello";
str[0] = 'M'  //No warning or error, just Undefined Behavior

The above sets str to point to the literal value "Hello" which is hard-coded in the program's binary image, which is flagged as read-only in memory, means any change in this String literal is illegal and that would throw segmentation faults.

CASE 2:

const char *str = "Hello";
str[0] = 'M'  //Compiler issues a warning

CASE 3:

char str[] = "Hello";
str[0] = 'M'; // legal and change the str = "Mello".

CASE 1:

char *str = "Hello";
str[0] = 'M'  //Warning may be issued by compiler, and will cause segmentation fault upon running the programme

The above sets str to point to the literal value "Hello" which is hard-coded in the program's binary image, which is flagged as read-only in memory, means any change in this String literal is illegal and that would throw segmentation faults.

CASE 2:

const char *str = "Hello";
str[0] = 'M'  //Compile time error

CASE 3:

char str[] = "Hello";
str[0] = 'M'; // legal and change the str = "Mello".
Source Link
Mohit
  • 915
  • 9
  • 7

CASE 1:

char *str = "Hello";
str[0] = 'M'  //No warning or error, just Undefined Behavior

The above sets str to point to the literal value "Hello" which is hard-coded in the program's binary image, which is flagged as read-only in memory, means any change in this String literal is illegal and that would throw segmentation faults.

CASE 2:

const char *str = "Hello";
str[0] = 'M'  //Compiler issues a warning

CASE 3:

char str[] = "Hello";
str[0] = 'M'; // legal and change the str = "Mello".