更改外部变量的值 [英] Changing the value of an external variable

查看:90
本文介绍了更改外部变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在File1.c中

We have in File1.c

int arr[10];

在File2.c中

extern int *arr;

int main()

{
   arr[0]=10;
   return 0;
}

这可能会发生什么问题,为什么?

What are the problems that can occur with this and why?

推荐答案

数组不是指针.内存访问将是错误的.

An array isn't a pointer. The memory access will be wrong.

File1.c中,您具有内存布局:

In File1.c, you have the memory layout:

+---+---+---+---+---+---+---+---+---+---+
+ 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
+---+---+---+---+---+---+---+---+---+---+
^
arr

File2.c中,您已经告诉编译器您具有内存布局:

In File2.c, you've told the compiler you have the memory layout:

+-------+
|  ptr  |
+-------+
^
arr

指针可能指向可以存储整数的位置.

where the pointer presumably points somewhere that an integer can be stored.

为了从extern int arr[];访问extern int *arr;,编译器必须采取完全不同的操作.

The compiler has to do things totally differently to access extern int *arr; from extern int arr[];.

如所写,最有可能的结果是崩溃,因为编译器取消引用空指针.但是,该行为是不确定的,并且一切皆有可能.您已经对编译器撒谎了;编译器将自行恢复—它不喜欢被骗.

As written, the most likely result is a crash as the compiler dereferences a null pointer. The behaviour is undefined, though, and anything is possible. You've lied to the compiler; the compiler will get its own back — it does not like being lied to.

这篇关于更改外部变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆