简体   繁体   中英

Printing Pointer Data with Printf in C

My understanding is that when you declare a pointer, say int *a = 5 , a is the pointer, and *a is the int pointed to - so the * indicates you're accessing the pointer data. (And the & is accessing the address). Hopefully this is correct?

How come when I'm doing printf it doesn't seem to work the way I want?

int main()
{
    int *a = 5;
    printf("%d\n",a);
    return 0;
}

This gives me the correct result, which I didn't expect. When I did *a instead of a in the printf, it failed, which I'm confused with?

Nopes, int *a = 5; does not store an int value of 5 into the memory location pointed by a , the memory location itself is 5 (which is mostly invalid). This is an initialization statement, which initializes the variable a which is of type int * (a pointer) to 5 .

For ease of understanding, consider the following valid case

int var = 10;
int *ptrVar = &var;

here, ptrVar is assigned the value of &var , the pointer. So, in other words, ptrVar points to a memory location which holds an int and upon dereferencing ptrVar , we'll get that int value.

That said, in general,

  printf("%d\n",a);

is an invite to undefined behavior , as you're passing a pointer type as the argument to %d format specifier.

The declaration int *a does declare a to be a pointer. Thus, the declaration

int *a = 5;

initializes a with the value 5. Just like how

int i = 5;

would initialize i with the value 5.

There are very few situations where you would want to initialize a pointer variable with a literal value (other than 0 or NULL). Those would likely be embedded (or otherwise esoteric) applications where certain addresses have a defined meaning on a particular platform.

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