简体   繁体   中英

Strings using char pointers

#include<stdio.h>
 int main(void)
 {
   char s='a',*j;
   j=&s;
   *j='b';
   printf("s is %c",s);
 }

Output: s is b.

From This program we get that we can change the values assigned to constant char by changing the value of the pointer.

But this doesnt happen with the following program.

#include<stdio.h>
int main(void)
{
  char *p="Hello";
  *p='z';   //By assuming that it should change 'H' as *p points to address of H//
  printf("%c",*p);
}

Output: Segmentation Fault Core dumped

Shouldnt even in this case the value of the 0th char in the Hello change as we are manipulating its pointer,doesnt *p point to the value at address of H.Shouldnt the output expected here be "zello".

From This program we get that we can change the values assigned to constant char by changing the value of the pointer.

There is no "constant char" in your first snippet. It is just a variable of type char initialized with some value. It is allocated in RW memory, so you can take it's address and modify the content.

In the second snippet you define a pointer and assign it with an address of a string literal , which is allocated in a memory which is not supposed to be written (often it is read only, or it's just an undefined behavior writing to it).

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