Green goblin
Green goblin

Reputation: 9994

Casting pointer & its address to integer pointer

What is the difference between the following two assignments?

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

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

I am very much confused about the behavior of the two declarations.
When should i use one over the other?

Upvotes: 1

Views: 3538

Answers (4)

John Bode
John Bode

Reputation: 123598

Types matter.

The expression p has type int * (pointer to int), so the expression &p has type int ** (pointer to pointer to int). These are different, incompatible types; you cannot assign a value of type int ** to a variable of type int * without an explicit cast.

The proper thing to do would be to write

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

You should never use an explicit cast in an assignment unless you know why you need to convert the value to a different type.

Upvotes: 0

Ashutosh
Ashutosh

Reputation: 169

#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;
}

Upvotes: 1

perreal
perreal

Reputation: 98118

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 */
}

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258678

int* q = (int*)p;

Is correct, albeit too verbose. int* q = p is sufficient. Both q and p are int pointers.

int* r = (int*)&p;

Is incorrect (logically, although it might compile), since &p is an int** but r is a int*. I can't think of a situation where you'd want this.

Upvotes: 9

Related Questions