C 将指针及其地址转换为整数指针

C 将指针及其地址转换为整数指针,c,C,以下两个作业的区别是什么 int main() { int a=10; int* p= &a; int* q = (int*)p; <------------------------- int* r = (int*)&p; <------------------------- } 我对这两个声明的行为感到非常困惑。 什么时候我应该使用一个而不是另一个 是正确的,尽管过于冗长。int*q=p就足够了。q和p都是int指针 int*

以下两个作业的区别是什么

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

    int* q = (int*)p; <-------------------------
    int* r = (int*)&p; <-------------------------
}
我对这两个声明的行为感到非常困惑。 什么时候我应该使用一个而不是另一个

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

int* r = (int*)&p;
逻辑上是不正确的,尽管它可能会编译,因为&p是int**而r是int*。我想不出你会想要这个

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 */
}
是正确的,尽管过于冗长。int*q=p就足够了。q和p都是int指针

int* r = (int*)&p;
逻辑上是不正确的,尽管它可能会编译,因为&p是int**而r是int*。我想不出你会想要这样的情况。

类型很重要

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 */
}
表达式p的类型为int*指向int的指针,因此表达式&p的类型为int**pointer指向指向int的指针。这是不同的、不兼容的类型;如果没有显式转换,则无法将int**类型的值分配给int*类型的变量

正确的做法是写作

int  *q = p;
int **r = &p;
除非您知道为什么需要将值转换为其他类型,否则决不能在赋值中使用显式强制转换

类型很重要

表达式p的类型为int*指向int的指针,因此表达式&p的类型为int**pointer指向指向int的指针。这是不同的、不兼容的类型;如果没有显式转换,则无法将int**类型的值分配给int*类型的变量

正确的做法是写作

int  *q = p;
int **r = &p;
除非您知道为什么需要将值转换为其他类型,否则决不能在赋值中使用显式强制转换