I am learning about C pointers and addresses for the first time and how to use them on my tablet
Let's say:
int x = 1, y = 2;
int *ip; // declares *ip as an int type?
ip = &x; //assigns the address of x to ip?
y = *ip; //y is now 1 via dereferencing
Are all the comment explanations correct?
What happens if I print the result of ip? Will it print the address of variable x, something like
011001110
The format to print output in C is given as – printf(“<format specifier>”, <variable to be printed>). The address of a variable is an integer numeric quantity and the format specifier used to print such a quantity is “%p” (for printing address in hexadecimal form) and “%lld” (for printing address in decimal form).
In C we have seen different format specifiers. Here we will see another format specifier called %p. This is used to print the pointer type data.
Yes. All of your statements are correct. However in case of first
int *ip;
it is better to say that ip
is a pointer to an int
type.
What happens if I print the result of ip?
It will print the address of x
.
Will it print the address of variable x, something like
011001110
No. Addresses are generally represented in hexadecimal. You should use %p
specifier to print the address.
printf("Address of x is %p\n", (void *)ip);
NOTE:
Note that in the above declaration *
is not the indirection operator. Instead it specify the type of p
, telling the compiler that p
is a pointer to int
. The *
symbol performs indirection only when it appears in a statement.
int x = 1, y = 2;
int *ip; // declares ip as a pointer to an int (holds an address of an int)
ip = &x; // ip now holds the address of x
y = *ip; // y now equals the value held at the address in ip
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With