当我给printf一个指向char数组的指针时程序崩溃

Whi*_*ger 5 c

当我尝试运行以下代码时,我得到一个seg错误.我已经尝试通过gdb运行它,我知道错误是作为调用的一部分发生的printf,但我迷失了为什么它无法正常工作.

#include <stdlib.h>
#include <stdio.h>

int main() {
  char c[5] = "Test";
  char *type = NULL;

  type = &c[0];
  printf("%s\n", *type);
}
Run Code Online (Sandbox Code Playgroud)

如果我更换printf("%s\n", *type); ,printf("%s\n", c);我按照预期打印"测试".为什么它不能用于指向char数组的指针?

cni*_*tar 15

你正在通过一个平原char,printf并试图取消引用它.试试这个:

printf("%s\n", type);
              ^ 
Run Code Online (Sandbox Code Playgroud)

如果你传递*type它就像告诉printf"我在T位置有一个字符串".

type = &c[0]有点误导.你为什么不这样做:

type = c;
Run Code Online (Sandbox Code Playgroud)


Pho*_*non 5

不要取消引用type.它必须保持指针.