的类型test2是char *。因此, 的类型&test2将与的char **参数类型兼容。
的类型是。因此, 的类型将与的参数类型不兼容。xprintchar()
testchar [256]&testchar (*)[256]xprintchar()
让我向您展示 和 的地址方面的test区别test2。
#include <stdio.h>
#include <stdlib.h>
static void printchar(char **x)
{
printf("x = %p\n", (void*)x);
printf("*x = %p\n", (void*)(*x));
printf("Test: %c\n", (*x)[0]);
}
int main(int argc, char *argv[])
{
char test[256];
char *test2 = malloc(256);
test[0] = 'B';
test2[0] = 'A';
printf ("test2 : %p\n", (void*)test2);
printf ("&test2 : %p\n", (void*)&test2);
printf ("&test2[0] : %p\n", (void*)&test2[0]);
printchar(&test2); // works
printf ("\n");
printf ("test : %p\n", (void*)test);
printf ("&test : %p\n", (void*)&test);
printf ("&test[0] : %p\n", (void*)&test[0]);
// Commenting below statement
//printchar((char **) &test); // crashes because *x in printchar() has an invalid pointer
free(test2);
return 0;
}
输出:
$ ./a.out
test2 : 0x7fe974c02970
&test2 : 0x7ffee82eb9e8
&test2[0] : 0x7fe974c02970
x = 0x7ffee82eb9e8
*x = 0x7fe974c02970
Test: A
test : 0x7ffee82eba00
&test : 0x7ffee82eba00
&test[0] : 0x7ffee82eba00
这里要注意的一点:
test2和的输出(内存地址)在&test2[0]数字上相同,它们的类型也相同,即char *.
但是test2和&test2是不同的地址,它们的类型也不同。
的类型test2是char *。
的类型&test2是char **。
x = &test2
*x = test2
(*x)[0] = test2[0]
和的输出(内存地址)在数值上相同,test但它们的类型不同。
的类型是。
的类型是。
的类型是。 &test&test[0]
testchar [256]
&testchar (*) [256]
&test[0]char *
如输出所示&test,与 相同&test[0]。
x = &test[0]
*x = test[0] //first element of test array which is 'B'
(*x)[0] = ('B')[0] // Not a valid statement
因此,您遇到了分段错误。