-1

in this C program when i am using

printf("%c",*(name+5));

then program works fine but when i am using

*(name+5) = '#';

then program causes crash

#include <stdio.h>
void main(void)
{
    char * name;
    name ="Hello World !";
    puts(name);
    *(name+5) = '#'; // here is error 
    puts(name);
}
alter_igel
  • 6,899
  • 3
  • 21
  • 40
SURAJ
  • 1
  • 1

1 Answers1

3

With...

char * name;
name ="Hello World !";
*(name+5) = '#';

you are manipulating the contents of a string literal, which is undefined behaviour, likely a crash.

Make an array out of it, which you may alter then:

char name[] ="Hello World !";
name[5] = '#';

or:

char buffer[] ="Hello World !";
char *name = buffer;
*(name+5) = '#';

Note that here the contents of string literal "Hello World!" are copied into an array which's content you are allowed to change.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58