C: Behaviour of arrays when assigned to pointers

前端 未结 4 1540
名媛妹妹
名媛妹妹 2021-01-27 20:17
#include 

main()
{
  char * ptr;

  ptr = \"hello\";


  printf(\"%p %s\" ,\"hello\",ptr );

  getchar();

}

Hi, I am trying to underst

4条回答
  •  渐次进展
    2021-01-27 20:56

    Say what?

    Your code allocates 6 bytes of memory and initializes it with the values 'h', 'e', 'l', 'l', 'o', and '\0'.

    It then allocates a pointer (number of bytes for the pointer depends on implementation) and sets the pointer's value to the start of the 5 bytes mentioned previously.

    You can modify the values of an array using syntax such as ptr[1] = 'a'.

    Syntactically, strings are a special case. Since C doesn't have a specific string type to speak of, it does offer some shortcuts to declaring them and such. But you can easily create the same type of structure as you did for a string using int, even if the syntax must be a bit different.

提交回复
热议问题