Why don't I need to dereference a character pointer in C before printing it?

后端 未结 6 1227
遇见更好的自我
遇见更好的自我 2020-12-13 11:19

Why does this code work? I would expect that I would need to dereference ptr, printf(\"%s\\n\", *ptr); before I could print it out, but I get a

6条回答
  •  温柔的废话
    2020-12-13 12:14

    The %s formatter to printf expects a "string", which is really a pointer to a null-terminated array of characters.

    That is to say, printf expects you to pass the pointer to it. When you dereference the pointer, it's taking the letter J, whose value in ascii is 74 (decimal), and tries treating that as a pointer to an array. That's an area of memory that's inaccessible, so you get the segmentation violation.

提交回复
热议问题