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

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

问题描述

文件 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?

推荐答案

数组分解,或者在作为参数传递给函数时隐式转换为指针,或在右侧转换为右值时赋值运算符.所以就像:

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 对象的指针,因此您实际上是在尝试取消对某个未指向任何位置的内存位置的引用有效(即,array 中的第一个槽是一个数字整数值,如 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;

这仍然有效,因为 array 再次隐式转换为指向保存整数值序列的内存块的指针,然后取消引用以获取第一个序列中的值.但是在您的情况下,通过将您的数组声明为当前代码模块作为外部定义的指针,而不是数组,它将跳过通常完成的隐式转换为指针,并像使用数组对象一样使用它是指向对象本身的指针,而不是对象数组.

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.

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

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