Home > OS >  How to change the variable value without changing its * value?
How to change the variable value without changing its * value?

Time:02-10

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

CodePudding user response:

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.

CodePudding user response:

You do not change the value of a, but of a copy of a, you change the value.

Once you initialized b=&a and don't change the value of b (equal to the address of a), all the time a == *b will be true.

What you may want to do is so:

void increment(int *value) {
    (**(&value))  ;
}

and call it so: increment(&a). After habing incremented, b=&a is still true, however you change the a.

  • Related