简体   繁体   中英

Pointer unexpectedly pointing to a value and not an address

int changeValue(int *a) {
    *a = 4;
     printf("a points to: %d\n", a);
     return 0;

}
int main() {
    int* b = NULL;
    printf("b points to : %d \n",b);
    changeValue(&b);
    printf("b points to : %d\n", b);
}

The output I get is that b points to 0, a points to some address -- all as expected -- but then suddenly I get b points to 4.

Why is it not pointing to an address?

I have also noticed if I try to display the actual value of *b I get a read access violation

You can't get value of nullptr, this will raise a nullptr exception.

#include <stdio.h>
int changeValue(int* a) {
    *a = 4;
    printf("a points to: %p a's value is: %d\n", a, *a);
    return 0;
}
int main() {
    int a = 0;
    int* b = &a;
    printf("b points to : %p \n", b);
    changeValue(b);
    printf("b points to : %p\n", b);
    return 0;
}

It generates 4 warnings on gcc, so I will break it down.

  1. In changeValue function, make it a while printing, or else you get a warning that %d was expected while you gave an int
  2. In main, printf for b shows address pointed to and not value of b.
  3. Make the function to changeValue(b) because b is already a pointer.

Now, note that %d and b still generate a warning here but this is just to show the output.

#include<stdio.h>
int changeValue(int *a) {
    *a = 4;
     printf("a points to: %d\n", *a);
     return 0;
}

int main() {
    int* b = NULL;
    int a = 999;
    printf("b points to : %d \n",b);
    b = &a;
    printf("b has address %d points to : %d \n",b, *b);
    changeValue(b);
    printf("b points to : %d\n", *b);
}

If I run the above code, the following is what I obtain as output.

b points to : 0
b has address 799914380 points to : 999
a points to: 4
b points to : 4

Now we can see that printf with %d and only a pointer b prints its address while *b prints its value. Note that if you try to *b when b is NULL, you will get segfaults.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM