指针数组的extern问题 [英] Pointer-array-extern question

查看:258
本文介绍了指针数组的extern问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文件1.C

int a[10];

main.c文件:

extern int *a;

int main()
{
    printf("%d\n", a[0]);
    return 0;
}

给我一个段错误!这是怎么回事了?

Gives me a segfault! What's going wrong?

推荐答案

阵列分解,或者传递时,一个函数作为参数,或者是隐式转换为指针时转换为r值在右手边的赋值操作符。因此,像:

Arrays decompose, or are implicitly converted to pointers when passed to a function as an argument, or when converted to an r-value on the right-hand-side of the assignment operator. So something like:

int array[10];
int* a = array;  //implicit conversion to pointer to type int

void function(int* a);
function(array);  //implicit conversion to pointer to type int

工作得很好。但是,并不意味着,数组本身是指针。所以,如果你像对待你已经做了指针数组,你实际上是处理数组类型,如果是持有的地址的指针 INT 目的。由于您的数组实际上是 INT 的对象序列,而不是指向 INT 的对象,你实际上是试图解引用到不指向任何地方有效(即在第一个插槽阵列是一个数字的整数像 0 这将是像取消对NULL)。所以这就是为什么你段错误。需要注意的是,如果你做了这样的事情:

works just fine. But that does not mean that arrays themselves are pointers. So if you treat an array like a pointer as you've done, you're actually treating the array type as-if it was a pointer that held the address to an int object. Since your array is actually a sequence of int objects, and not pointers to int objects, you're actually trying to dereference to some memory location that isn't pointing to anywhere valid (i.e., the first slot in array is a numerical integer value like 0 which would be like dereferencing a NULL). So that is why you're segfaulting. Note that if you had done something like this:

int array[] = { 1, 2, 3, 4, 5};
int b = *array;

这仍然有效,因为阵列再次被隐式转换为指针,持有整数值的序列,是内存块,然后解除引用得到的值第一序列。但是,在你的情况,通过声明你的数组到当前code模块作为外部定义的指针,而不是一个数组,它会跳过隐式转换到正常做一个指针,只是使用数组对象 - 如果它是一个指向对象本身,而不是一个数组对象。

That still works, since array is again implicitly converted to a pointer to the memory block that is holding a sequence of integer values and is then dereferenced to get the value in the first sequence. But in your case, by declaring your array to the current code module as an externally defined pointer, and not an array, it will skip over the implicit conversion to a pointer that is normally done, and just use the array object as-if it were a pointer to an object itself, not an array of objects.

这篇关于指针数组的extern问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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