简体   繁体   中英

how to print the value of a pointer from a structure

The value contained in the pointer 'p' from the structure below is wrong printed and i can not find the way to print it right. What's the right code for it? The code:

#include <stdio.h>

struct my_struct{ //structure definition
    int a,*p;
};

int main(){

    my_struct var;
    var.a = 5;                  //variable definition
    var.p = &(var.a);           //pointer gets address from variable
    printf("%d\n",var.p);       // the number 2686744 is printed instead of the number '5'

    return 0;
}

The %d format specifier to printf expects an int , but you're passing it an int * .

You need to dereference the pointer to obtain an int :

printf("%d\n",*(var.p));

You are printing the literal address of the pointer (ie not the value it points to, but the address in memory of where it points) when you write printf("%d\\n", var.p) . To access the value pointed to you need to dereference the pointer with printf("%d\\n", *(var.p)) .

As a side note: if you ever do want to access the address of a pointer for whatever reason in a printf family function, use the %p format specifier instead: http://www.cplusplus.com/reference/cstdio/printf/

You're not dereferencing the pointer

my_struct var;
var.a = 5;                  
var.p = &(var.a);           
printf("%d\n",*(var.p)); //this will work    

Use *var.p at print to dereference the pointer p and get it's value. Right now you are printing the memory location in decimal.

Your pointer var.p is simply containing an address. When i say containing, i mean it's value is an address. In your case, this is the var.a's address. When you try to print its value , you will print the var.a's address.

If you want to print what is CONTAINED at this address, or what is the VALUE at this address, you have to put a star before it.

In your case, you do not want to print var.p's value , as this an address, but you want to print the value contained at this address, using *(var.p).

Take care, there may be a difference in some languages between " var.p" and " (var.p)". Imagine these operations in mathematics : (2x3)² and 2x3². On the first operation, the ² will affect the whole multiplication, when, in the second operation, the ² will only affect the number 3.

In fact, you may want to try it by yourself to know how the language you are using work, *var.p may give you a way different result :) However, using parenthesis in this case is a good practice, even if the language does give the same result.

PS : Just an extra information, if you ever need to print an address (which is not your case at the moment, you only want to print a decimal) using printf, replace %d by %p.

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