Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C pointer address printing

Tags:

c++

c

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

like image 632
Robert Rocha Avatar asked Jan 14 '14 02:01

Robert Rocha


People also ask

How do I print an address from printf?

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).

What does %P in C print?

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.


2 Answers

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.

like image 165
haccks Avatar answered Oct 07 '22 03:10

haccks


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
like image 4
Andrew L Avatar answered Oct 07 '22 03:10

Andrew L