指针在C中,一个示例作品,一个不是
我有这个代码:
#include <stdio.h>
int main(void) {
char greeting1[10] = "Hello!"; //works
char *greeting2 = "Hello!"; //works
int numbers1[10]= {1,2,3}; //works
int *numbers2 = {1,2,3}; //doesn't work
}
对我来说,使用指针适用于“ engering2”是没有意义的,而对于“ numbers2”而言。有没有一种简单的方法来解释为什么这不适用于“ numbers2”?
I have this code:
#include <stdio.h>
int main(void) {
char greeting1[10] = "Hello!"; //works
char *greeting2 = "Hello!"; //works
int numbers1[10]= {1,2,3}; //works
int *numbers2 = {1,2,3}; //doesn't work
}
It doesn't make sense to me that using pointers work for "greeting2", but not for "numbers2". Is there a simple way to explain why this does not work for "numbers2"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在表达式中使用的阵列将其转换为指针转换为其第一元素。
在此声明中,
字符串文字具有数组类型
char [7]
,并将其隐式转换为指向其第一个元素。此指针表达式用于初始化指针engreing2
。当字符串字面用来初始化数组时,则使用其元素(作为初始化器)来初始化数组的元素。
实际上,上述声明等同于
本声明中,
您正在尝试使用包含多个初始化器的支撑列表初始化标量对象。这样的初始化无效。要初始化标量对象,您可以在括号中仅使用一个初始化器。
您可以使用复合文字来初始化指针,例如
在这种情况下,具有数组类型
int [3]
再次被隐式转换为指向其第一个元素的指针,此地址用于初始化该指针指针数字2
。Arrays used in expressions with rare exceptions are converted to pointers to their first elements.
In this declaration
the string literal has the array type
char[7]
and is implicitly converted to a pointer to its first element. This pointer expression is used to initialize the pointergreeting2
.When a string literal is used to initialize an array then its elements are used (as initializers) to initialize elements of the array.
In fact the above declaration is equivalent to
In this declaration
you are trying to initialize a scalar object with a braced list that contains more than one initializer. Such an initialization is invalid. To initialize a scalar object you may use only one initializer in braces.
You could initialize the pointer with a compound literal like
In this case the compound literal having the array type
int[3]
again is implicitly converted to a pointer to its first element and this address is used to initialize the pointernumbers2
.