直接分配int阵列到指针
试图提高我的C概念,现在似乎所有的混乱都在:(当然,
这种方式将 arr
分配给
ptr
有效,因为我们说> arr []
会衰减到*arr
int arr[] = {1, 2, 3};
int *ptr = arr; // Access arr with ptr
,但直接将数组分配到*ptr
不起作用,
int *ptr = {1, 2, 3};
printf("%d\n", ptr[0]); // Segmentation fault
我的理解是 int arr [] = {}
具有特殊的含义,其中分配了一个连续的堆栈空间,并通过名称 arr
直接提及
尝试使用 int *ptr = { }
只是使编译器感到困惑?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
变量
ptr
是标量对象。您可以用一个仅包含一个表达式的支撑列表初始化标量对象。从C标准(6.7.9初始化)
因此,例如:
您可能会写:
这相当于:这是
没有意义的,并且编译器可以发出一条消息,即整数不会在不铸造的情况下转换为指针。
您可以使用复合文字来初始化指针,例如:
在此声明中,创建了一个
int [3]
的未命名数组,该数组的第一个元素的地址为分配给指针。The variable
ptr
is a scalar object. You may initialize a scalar object with a braced list that contains only one expression.From the C Standard (6.7.9 Initialization)
So instead of:
you may write for example:
that is equivalent to:
and does not make a sense and the compiler can issue a message that an integer is converted to a pointer without casting.
Instead of the braced list you could initialize the pointer with a compound literal like:
In this declaration there is created an unnamed array of the type
int[3]
and the address of the first element of the array is assigned to the pointer.{1,2,3}
并不意味着“一个数组”。在声明中,它是某些具有多个部分的对象的初始值列表。在
int arr [] = {1,2,3};
,{1,2,3}
是三个值的列表,用于初始化数组arr
。在
int *ptr = {1,2,3};
,{1,2,3}
将是用于初始化指针ptr 。但是
ptr
没有多个部分。它只有一个值,一个内存地址。因此{1,2,3}
将提供1
来初始化地址,这是一个问题,因为1
是int
int < /代码>,而不是地址,因此编译器应为此发出诊断消息。而且
2
或3
都没有什么可以初始化的,因此编译器应为此发出诊断消息。您可以使用复合文字直接在源代码中创建一个未命名的数组。复合文字具有表单
( type ){初始值}
。因此,您可以使用int
的数组使用(int []){1,2,3}
。您可以通过使用复合文字作为初始值来声明指针并将其初始化以指向数组
:到该地址。)
{1, 2, 3}
does not mean “an array”. In a declaration, it is a list of initial values for some object with multiple parts.In
int arr[] = {1, 2, 3};
,{1, 2, 3}
is a list of three values to use to initialize the arrayarr
.In
int *ptr = {1, 2, 3};
,{1, 2, 3}
would be a list of three values to use to initialize the pointerptr
. Butptr
does not have multiple parts. All it has is one value, a memory address. So{1, 2, 3}
would provide1
to initialize the address, which is a problem because1
is anint
, not an address, so the compiler should issue a diagnostic message for that. And there is nothing for2
or3
to initialize, so the compiler should issue a diagnostic message for that.You can use a compound literal to create an unnamed array directly in source code. A compound literal has the form
(type) { initial values }
. So you can create an array ofint
with(int []) {1, 2, 3}
.You can declare a pointer and initialize it to point to an array by using a compound literal as the initial value:
(Note that the array is automatically converted to a pointer to its first element, so
ptr
is initialized to that address.)