Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change the variable value without changing its * value?

I am a newbie in the C language and learning it. I am learning the pointers. I am confused a little about the following program.

My question is it even possible to get the outcome B ever? I am changing the value of a but accordingly, the value of b gets changed due to the pointer and I am always just getting outcome A. How can I get outcome B? Any help will be really appreciated. Thanks 🙂

#include <stdio.h>
 void increment(int value) {
    value++;
}
int main() {
   int a = 6;
   int *b = &a;
   increment(a); 
   if(a == *b) {
     printf("outcome A");
   } else if(a > *b) {
     printf("outcome B");
   } else {
     printf("outcome C");
   } return 0;
} 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A pointer is an object in many programming languages that stores a memory address. A pointer references a location in memory, and obtaining the value stored at that location is known as dereferencing the pointer

Take a look at this code snippet

#include <stdio.h>

int main() {
   int a = 6;
   int *b = &a;
   
   printf("a = %d  b = %p  *b = %d\n", a, (void*)b, *b); 
    
   a = 20;

   printf("a = %d  b = %p  *b = %d\n", a, (void*)b, *b); 
} 

Output:

a = 6  b = 0x7fff3ead8d6c  *b = 6
a = 20  b = 0x7fff3ead8d6c  *b = 20

As you can see, assigning a new value to a did not change the value of b. It did change the value pointed to by b, however. That is, b did not change, while *b did.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading