以下代码会导致垃圾或访问冲突错误,为什么会这样......?
file1.c
int a[3]={1,39,7}; /* definition */
file2.c
extern int a[]; /* declaration */
b = a[2]; /* correct usage in file2.c */
file3.c
extern int *a; /* another declaration */
c = a[1]; /* a[1] is *(a+1), fails! */
file2中的用法获取a的第3个元素(7),但是 file2 中的用法将 39 解释为地址(假设 32 位整数和地址),导致垃圾或 访问冲突错误为什么会这样......?
file1.c
int a[3]={1,39,7}; /* definition */
file2.c
extern int a[]; /* declaration */
b = a[2]; /* correct usage in file2.c */
file3.c
extern int *a; /* another declaration */
c = a[1]; /* a[1] is *(a+1), fails! */
The usage in file2 obtains the 3rd element (7) of a, but the
usage in file2 interprets 39 as an address (assuming 32
bit integers and addresses), resulting in either garbage or
access violation error why is it so...?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请参阅 C 常见问题解答中的此答案。
int *a
和int a[]
不一样!编辑:
从那里的答案修改:
编辑#2:
要了解发生了什么,请查看此答案。修改相关部分以适合您的样品:
所以在 file3.c 中,它认为 a 是一个指针,它被取消引用。由于它实际上是数组本身,因此它被取消引用到其他地方,这会导致访问冲突。
Look at this answer in the C FAQ.
int *a
andint a[]
are not the same!EDIT:
Modified from the answer there:
EDIT #2:
To see what happens, look at this answer. The relevant parts, modified to fit your sample:
So in file3.c it believes a to be a pointer, which is dereferenced. Since it actually is the array itself, this is dereferenced to somewhere else, which results in the access violation.