我需要帮助理解“指向N Integers”数组的正确用法。初始化
以下声明:
int(*x)[10]
被定义为 x是通往10个元素整数数组的整数指针。
问题1 :这是否意味着 x 最初指向10个整数数组的第一个元素?如果是这样,那么这与简单 int x [10]
有何不同?
问题2 :如果 int(*x)[10]
是不同的,那么它有何不同,其实际用法的某些实例是什么?
问题3 :我试图编写一个简单的程序访问,写入和打印数组元素。
#include <stdio.h>
void main()
{
int (*x)[12], i;
for(i = 0; i <= 11;)
{
(*x)[i] = i;
printf("%d\n", (*x)[i++]);
}
}
当我运行时,我会不断得到分割故障。我知道,当我尝试访问无法访问的内存时,会发生细分故障。但是我只访问我初始化的12个元素。那为什么我的程序会以细分故障退出呢?另外,我是否正确访问数组( (*x)[i] = i
),还有其他访问它的方法吗?
The following declaration:
int (*x)[10]
is defined as x is an integer pointer to an integer array of 10 elements.
Question 1 : Doesn't this mean that x initially points to the first element of an array of 10 integers? If so, then, how is this different from the simple int x[10]
?
Question 2 : If int (*x)[10]
is different, then how is it different and what are some instances of its practical usage?
Question 3 : I was trying to write a simple program access, write to and print the array elements.
#include <stdio.h>
void main()
{
int (*x)[12], i;
for(i = 0; i <= 11;)
{
(*x)[i] = i;
printf("%d\n", (*x)[i++]);
}
}
I keep getting a segmentation fault when I run it. I understand that a segmentation fault occurs when I try to access memory that I don't have access to. But I am only accessing the 12 elements that I have initialized. Then why does my program exit with a segmentation fault? Also, am I accessing the array ((*x)[i] = i
) correctly and are there other ways to access it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于根据C标准的初学者,没有参数的功能主体应
像所示程序中的函数
一样贴发。因此,将指针删除
导致不确定的行为。
取而代之的是,您可以写作,例如
一样写入该程序会更简单,
,如果该程序像在此声明中
将其隐式转换为指向其类型
int *
的第一个元素的指针。在此声明中,
初始化表达式
&amp; a
已经是类型int( *)[n]
的指针。因此,在表达式中,
子表达
*x
产生数组a
的lvalue。因此,实际上,上述表达式等同于指针中都关注
在声明和
x
存储数组a
的记忆范围的起始地址,但不同类型。删除第一个指针,您将获得数组a
的第一个元素。取消第二个指针,您将获得整个数组本身。For starters according to the C Standard the function main without parameters shall be decalred like
In the shown program you declared an uninitialized pointer
that has an indeterminate value. So dereferencing the pointer
results in undefined behavior.
Instead you could write for example
Though the program will look simpler if to write it like
In this declaration
is implicitly converted to a pointer to its first element of the type
int *
.In this declaration
the initializing expression
&a
is already a pointer of the typeint ( * )[N]
.So in the expression
the subexpression
*x
yields lvalue of the arraya
. So in fact the above expression is equivalent toPay attention to that in the both declarations
and
the pointers
x
store the starting address of the memory extent occupied by the arraya
but have different types. Dereferencing the first pointer you will get the first element of the arraya
. Dereferencing the second pointer you will get the whole array itself.