Will this memory address not be after this assignment?

int *p = NULL ,c , *q;
c=10;
p = &c;
q = p; 

printf ("%d and %d ",&p, &q );

      

Output:

2686788 and 2686780

      

My question is, as far as I am guessing, I thought the memory address would be the same as I assigned p

in q

. Maybe I'm wrong.

+3


source to share


4 answers


p

and q

are two different variables, and their addresses are different. &p

and &q

- addresses p

and q

respectively.
Content p

and q

will be the same, i.e., Will contain the same memory address after assignment

q = p;      

      

p

and q

both point to the same memory location. As for illustration, it is shown in the below ASCII text:

          p                          
      +-------+                      
      |       |                 c    
0x200 | 0x100 +---------+   +-------+
      |       |         +-> |       |
      +-------+             |  10   |
          q             +-> |       |
      +-------+         |   +-------+
      |       |         |     0x100  
0x300 | 0x100 +---------+            
      |       |                      
      +-------+                      


        p = q but &p != &q           

      




NOTE. To print the data type of the pointer, use the %p

specifier in printf

.

 printf ("%p and %p ", (void *)&p, (void *)&q );       

      

+15


source


You are misleading the content of the variables with their address . In this case, the content of p and q is the address of c. However, being different variables, their addresses will always be different.



+2


source


You are specifying the address of a variable, not the address it points to.

Both p and q point to the same address, but are different variables, so they have different addresses.

i.e:

c (address: 1000) โ†’ 10

p (address: 1010) โ†’ 1000

q (address: 2020) โ†’ 1000

change this value and you will see the value you want.

int *p = NULL ,c , *q;
c=10;
p = &c;
q = p; 

printf ("%p and %p ",p, q );

      

% p prints the address pointed to by the pointer.

+1


source


You are printing the address of the pointers themselves, not the values โ€‹โ€‹of the pointer:

// Prints the memory location of the pointers
printf ("%d and %d\n", &p, &q);

// Prints the values of the pointers
printf ("%d and %d\n",  p,  q);

// Prints the values that the pointers point to
printf ("%d and %d\n", *p, *q);

      

+1


source







All Articles