首先要理解
“数组不是指针”。
int p[] = (int []) {1,2,3,4,5,6};
在上述情况中,
p
是一个整数数组。将元素
{1,2,3,4,5,6}
复制到
p
中。这里不需要进行类型转换,因为
rvalue
和
lvalue
的类型都匹配,都是整数数组,所以不会出错。
int *p[] = (int *[]) {{1,2,3},{4,5,6}};
在上述情况下,
p
是一个整数指针数组。但是
{{1,2,3},{4,5,6}}
是一个二维数组(即[][]),不能强制转换为指针数组。您需要这样初始化 -
int p[][3] = { {1,2,3},{4,5,6} };
// ^^ First index of array is optional because with each column having 3 elements
// it is obvious that array has two rows which compiler can figure out.
但是,为什么这个语句编译通过了?
char *p[] = {"one", "two"...};
字符串字面值与整数字面值不同。在这种情况下,
p
也是一个字符指针数组。当实际上说了
"one"
时,
它可以被复制到一个数组中,或者将其视为只读并指向其位置。
char cpy[] = "one" ;
cpy[0] = 't' ; // Not a problem
char *readOnly = "one" ;
readOnly[0] = 't' ; // Error because of copy of it is not made but pointing
// to a read only location.
使用字符串字面值时,上述任一情况均可。因此,该语句编译通过。但是 -
char *p[] = {"one", "two"...}; // All the string literals are stored in
// read only locations and at each of the array index
// stores the starting index of each string literal.
我不想告诉编译器数组有多大。
使用 malloc
动态分配内存是解决方案。
希望能帮到你!
int p[] = (int []) {1,2,3,4,5,6};
在 Linux 上使用 gcc 4.8.2 会出现错误。错误信息为“array initialized from non-constant array expression”。请问您的 gcc 版本是多少? - Albert Netymk