指针为int"&之间的差异QUOT;和"指向整数&QUOT的阵列; [英] Difference between "pointer to int" and "pointer to array of ints"

查看:107
本文介绍了指针为int"&之间的差异QUOT;和"指向整数&QUOT的阵列;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int main()
{
    int (*x)[5];                 //pointer to an array of integers
    int y[6] = {1,2,3,4,5,6};    //array of integers
    int *z;                      //pointer to integer

    z = y;
    for(int i=0;i<6;i++)
        printf("%d ",z[i]);

    x = y;
    for(int i=0;i<6;i++)
        printf("%d ",(*x)[i]);

    return 0;
}

以上两种printfs输出打印数字1至6结果
如果指向整数数组指向整数可以做同样的事情,他们有相同的内部重新presentation?结果
编辑:这code编译不作为时,由下面的答案中指出给予警告,但是它并使用正确打印数值我的两个x86_64的机器上的时间的gcc

Both the above printfs print numbers 1 through 6.
If both "pointer to array of integers" and "pointer to integer" can do the same thing, do they have the same internal representation?
This code does give warnings when compiled as pointed out by the answers below, however it does print the values correctly both the time on my x86_64 machine using gcc

推荐答案

首先,你的code将无法编译。该阵列的类型为 INT [6] (6元),而指针的类型 INT(*)[5] 。你不能让这个指针指向数组,因为该类型是不同的。

Firstly, your code will not compile. The array has type int[6] (6 elements), while the pointer has type int (*)[5]. You can't make this pointer to point to that array because the types are different.

其次,当你初始化(分配)这样的指针,你必须使用&安培; 阵列上: X =&放大器;是,不只是一个普通的 X = Y 作为您code。

Secondly, when you initialize (assign to) such a pointer, you have to use the & on the array: x = &y, not just a plain x = y as in your code.

我假设你只需键入,而不是复制粘贴的code起来,真正的code。

I assume that you simply typed the code up, instead of copy-pasting the real code.

第三,有关内部重新presentation。一般来说,在实践中,你应该期望所有的数据指针使用相同的内部重新presentation。此外,上述的分配(如果写入正确地)之后,指针将具有相同的数值。 INT(*)之间的差值[5] 为int * 只存在于概念层面,即在一级语言:种类是不同的。它有一些后果。例如,如果你增加你的以Z 会跳转到数组的下一个成员,但如果你增加 ,它会跳整个数组等过那么,这些指针并不真正做同样的事情。

Thirdly, about the internal representation. Generally, in practice, you should expect all data pointers to use the same internal representation. Moreover, after the above assignments (if written correctly), the pointers will have the same numerical value. The difference between int (*)[5] and int * exists only on the conceptual level, i.e. at the level of the language: the types are different. It has some consequences. For example, if you increment your z it will jump to the next member of the array, but if you increment y, it will jump over the whole array etc. So, these pointers do not really "do the same thing".

这篇关于指针为int&QUOT;&之间的差异QUOT;和&QUOT;指向整数&QUOT的阵列;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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