C 关于将字符**转换为(字符*)的问题
如果我有下面的一段代码,为什么和如何工作?具体来说,x是什么(比如在malloc行中创建了什么?)以及为什么编译器允许我使用malloc将char**转换为(char*)C 关于将字符**转换为(字符*)的问题,c,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
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
这个代码不起作用 如果编译时带有警告,那么会有很多警告让用户知道 它实际上可以编译的原因是大部分操作都涉及指针。指针只是数字,所以可以将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
问题是什么?嗨,欢迎来到stack overflow。请花点时间阅读以了解抱歉,我做了一些编辑以澄清我的问题。如果编译器甚至没有警告一次,是时候扔掉它并获得一个新的。未定义的行为