1

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?

4 Answers 4

9
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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.