铸造指针&它的地址为整数指针

时间:2012-07-12 11:31:47

标签: c

以下两项作业有什么区别?

int main()
{
    int a=10;
    int* p=  &a;

    int* q = (int*)p; <-------------------------
    int* r = (int*)&p; <-------------------------
}

我对这两个声明的行为非常困惑 我应该何时使用其中一个?

4 个答案:

答案 0 :(得分:9)

int* q = (int*)p;

是正确的,尽管太冗长了。 int* q = p就足够了。 qp都是int指针。

int* r = (int*)&p;

不正确(逻辑上,虽然它可能会编译),因为&pint**rint*。我想不出你想要这个的情况。

答案 1 :(得分:1)

#include <stdio.h>
int main()
{
    int a = 10;   /* a has been initialized with value 10*/

    int * p = &a; /* a address has been given to variable p which is a integer type pointer
                   * which means, p will be pointing to the value on address of a*/

    int * q = p ; /*q is a pointer to an integer, q which is having the value contained by p,                     * q--> p --> &a; these will be *(pointer) to value of a which is 10;

    int * r = (int*) &p;/* this is correct because r keeping address of p, 
                         * which means p value will be pointer by r but if u want
                         * to reference a, its not so correct.
                         * int ** r = &p; 
                         * r-->(&p)--->*(&p)-->**(&p)                             
                         */
       return 0;
}

答案 2 :(得分:0)

int main()
{
    int a=10;
    int* p=  &a;

    int* q  = p; /* q and p both point to a */
    int* r  = (int*)&p; /* this is not correct: */
    int **r = &p; /* this is correct, r points to p, p points to a */

    *r = 0; /* now r still points to p, but p points to NULL, a is still 10 */
}

答案 3 :(得分:0)

类型很重要。

表达式p具有类型int *(指向int的指针),因此表达式&p具有类型int **(指向{{1的指针)的指针}})。这些是不同的,不兼容的类型;如果没有显式强制转换,则无法将类型int的值分配给int **类型的变量。

正确的要做的事情就是写

int *

除非您知道为什么需要将值转换为其他类型,否则不应在赋值中使用显式强制转换。

相关问题