简体   繁体   English

GCC关于为数组分配指针变量的警告?

[英]GCC warning about assigning a pointer variable with an array?

code snippet: 代码段:

int *c[2] = {{1,2,3}, {4,5,6}};

gives warning: 给出警告:

warning: incompatible integer to pointer conversion initializing 'int *' with an expression of type 'int'
      [-Wint-conversion]
    int *c[2] = {{1,2,3}, {4,5,6}};
                  ^
warning: excess elements in scalar initializer
    int *c[2] = {{1,2,3}, {4,5,6}};
                    ^

I suppose array {1,2,3} would decay to pointer so the assignment be legit? 我想数组{1,2,3}会衰减到指针,所以分配是合法的吗?

Further more, according to the warning, why does the compiler think i'm trying to assign int to int * ? 此外,根据警告,编译器为什么会认为我正在尝试将int分配给int * instead of int array type to int * ? 而不是int *int array type Thanks in advance! 提前致谢!

Bracketed initializers are not arrays, and so cannot undergo decay to a pointer type. 方括号括起的初始化程序不是数组,因此不能衰减到指针类型。 And because c is an array of int * , each initializer needs to be of that type. 并且由于cint *的数组,因此每个初始化程序都必须是该类型。 Nested initializers only work with actual arrays (not pointers) or structs. 嵌套的初始化程序仅适用于实际的数组(不适用于指针)或结构。

What you can do however is use compound literals in the initializer which do have an array type. 但是,您可以做的是在初始化器中使用具有数组类型的复合文字

int *c[2] = {(int []){1,2,3}, (int []){4,5,6}};

I suppose array {1,2,3} would decay to pointer so the assignment be legit? 我想数组{1,2,3}会衰减到指针,所以分配是合法的吗?

No. {1, 2, 3} is not an array, and no decay applies to it. {1, 2, 3}不是数组,并且没有衰减适用于它。 It is an initializer suitable for initializing an array of three or more elements of arithmetic type, but you are trying to use it to initialize a pointer. 它是一个初始化程序,适用于初始化由三个或更多算术类型的元素组成的数组,但是您尝试使用它来初始化指针。 You could do something like this, instead: 您可以执行以下操作:

static int x[] = { 1, 2, 3 };
static int y[] = { 4, 5, 6 };
int *c[] = { x, y };

Or you could use compound literals to avoid declaring variables x and y , as another answer suggests. 或者,您可以使用复合文字来避免声明变量xy ,如另一个答案所建议的那样。 In either of these cases, the initializer elements are arrays, and they do decay to pointers. 在这两种情况下,初始化器元素都是数组,并且它们确实会衰减到指针。

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

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