1

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

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

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

我对这两个声明的行为感到非常困惑。
我什么时候应该使用一个而不是另一个?

4

4 回答 4

10
int* q = (int*)p;

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

int* r = (int*)&p;

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

于 2012-07-12T11:33:34.600 回答
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;
}
于 2012-07-12T11:52:48.257 回答
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 */
}
于 2012-07-12T11:35:33.663 回答
0

类型很重要。

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

正确的做法是写

int  *q = p;
int **r = &p;

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

于 2012-07-12T14:31:53.053 回答