关于将char **转换为(char *)的问题

时间:2018-11-07 05:37:57

标签: c

如果我有以下代码,为什么以及如何工作?具体来说,x是什么(就像在malloc行中创建的东西一样?),为什么编译器允许我使用malloc将char **强制转换为(char *)。

char **x= (char *)malloc(1000);

*x="check\0";

printf("%s",x); //random bits in memory

printf("%c",x); //random bits in memory

x[0]='w';

x[1]='t';

x[2]='f';

x[3]='\0';

printf("%c",x); //random bits in memory

printf("%s",x); //w

1 个答案:

答案 0 :(得分:0)

此代码无效。

如果编译时带有警告,则有很多条警告会通知用户。

它实际上可以编译的原因是,大多数操作都涉及指针。指针只是数字,因此可以将char **指针放入char *的空间。这当然不能帮助程序真正起作用。

C标准没有将这些操作定义为错误,因此编译器允许它们通过。

$ gcc -g -Wall  example.c -o example
m.c: In function ‘main’:
m.c:7:12: warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
  char **x= (char *)malloc(1000);
            ^
m.c:11:10: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char **’ [-Wformat=]
 printf("%s",x); //random bits in memory
         ~^
m.c:13:10: warning: format ‘%c’ expects argument of type ‘int’, but argument 2 has type ‘char **’ [-Wformat=]
 printf("%c",x); //random bits in memory
         ~^
m.c:15:5: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
 x[0]='w';
     ^
m.c:17:5: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
 x[1]='t';
     ^
m.c:19:5: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
 x[2]='f';
     ^
m.c:23:10: warning: format ‘%c’ expects argument of type ‘int’, but argument 2 has type ‘char **’ [-Wformat=]
 printf("%c",x); //random bits in memory
         ~^
m.c:25:10: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char **’ [-Wformat=]
 printf("%s",x); //w