为什么这个指针做作会引发错误?

1 c pointers declaration pointer-to-pointer

最近开始研究指针,想知道为什么char *n = “hii”; char *p = &n;会显示error

#指向地址#

#include<stdio.h>
#include<string.h>
#include<cs50.h>


int main(void)
   {
        char *n = "hii";
        /*why the below line is showing the error as it has no impact on the result, below the pointer p is pointing to address of n*/
        char *p = &n;
        printf("%i\n", &n);              

   }
  
Run Code Online (Sandbox Code Playgroud)

yan*_*ano 5

这段代码发生了什么事情是一团糟:

int main(void)
{
  // initializes n to point to the string literal "hii". So far so good
  char *n = "hii";  
  // This is problem. It assigned the address of n (type char**) to p (type char*).
  // Your compiler should warn you about this.
  char *p = &n;
  // This is a problem. Trying to print the address of n (type char**) using the
  // %i format specifier, which is used for int types. To printf an address,
  // use the %p format specifier and cast the argument to void*.
  printf("%i\n", &n);
}
Run Code Online (Sandbox Code Playgroud)

您可以在此处查看所有警告。如果您的编译器没有产生这些警告,请打开它们或使用更好的警告。以下是此代码的“修复”:

int main(void)
{
  // This is fine
  char *n = "hii";  
  // This assignment is valid since p and n are the same type (char*), and both
  // point to the string literal "hii"
  char *p = n;
  // This prints the _address_ of n
  printf("%p\n", (void*)&n);
  // This prints the address of where the string literal "hii" is stored
  printf("%p\n", (void*)p);
  // these print the actual string
  printf("%s\n", n);
  printf("%s\n", p);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)