简体   繁体   English

char 的指针数组与 int 的指针数组

[英]Array of Pointer for char Vs Array of pointer for int

Why the first declaration is valid whereas the other is not?为什么第一个声明有效而另一个无效?

    char* string[2] = { "Hello", "Bellow" };

    int* b[2] = { {1,2,3}, {2,3,4} };

The reason is that the compiler is not able to imply the type from {1,2,3} , which is desired to be int[3] .原因是编译器无法暗示来自{1,2,3}的类型,而该类型希望是int[3] You can use array literal to specify it manually as int[3] or int[] :您可以使用数组文字手动将其指定为int[3]int[]

int *b[2] = { (int[]){1,2,3}, (int[]){2,3,4} };

However, you need to be careful because the lifetime of the literals is bound only to the block where they are defined.但是,您需要小心,因为文字的生命周期仅绑定到定义它们的块。

Unless it is the operand of the sizeof or unary & operators, or is a string literal used to initialize a character array in a declaration, an expression of type "N-element array of T " will be converted, or "decay", to an expression of type "pointer to T " and the value of the expression will be the address of the first element of the array.除非它是sizeof或一元&运算符的操作数,或者是用于在声明中初始化字符数组的字符串文字,否则“ T的 N 元素数组”类型的表达式将被转换或“衰减”为“指向T的指针”类型的表达式,表达式的值将是数组第一个元素的地址。

In the declaration在声明中

char* string[2] = { "Hello", "Bellow" };

the string literals are not being used to initialize a character array, but an array of pointers, so both strings "decay" to pointers to their first element, so you get字符串文字不是用来初始化字符数组,而是一个指针数组,所以两个字符串都“衰减”到指向它们第一个元素的指针,所以你得到

char *[2] = { char *, char * };

In the other declaration在另一个声明中

int* b[2] = { {1,2,3}, {2,3,4} };

{1,2,3} and {2,3,4} are not array expressions - they're initializer lists, and they don't "decay" to pointers. {1,2,3}{2,3,4}不是数组表达式- 它们是初始化列表,它们不会“衰减”到指针。 As tstanisl shows, you can use compound literals like正如 tstanisl 所示,您可以使用复合文字,例如

int *b[2] = { (int[]){1,2,3}, (int[]){2,3,4} };

and each of the compound literal expressions will decay to a pointer.并且每个复合文字表达式都将衰减为一个指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM