C address stamp pointer

I first learned about C pointers and addresses and how to use them on a tablet

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 commentary explanations correct?

What happens if I print the ip result? Will it print the address of the variable x, something like

011001110

+7
c ++ c
source share
4 answers

Yes. All your statements are true. However, in the case of the first

 int *ip; 

it is better to say that ip is a pointer to an int type.

What happens if I print the ip result?

It will output the address x .

Will it print the address of the variable x, something like

 011001110 

Not. Addresses are usually in hexadecimal format. You must use the %p specifier to print the address.

 printf("Address of x is %p\n", (void *)ip); 

Note:
Please note that in the above description * not an indirectness operator. Instead, it points to type p , telling the compiler that p is a pointer to an int . The symbol * performs an indirect transfer only when it appears in the instruction.

+23
source share
 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 
+2
source share

Consider the following as an example:

  Initializer xy ip
 Memory Value [1] [2] [1000]
 Memory Address 1000 1004 1008

As you can see:

  • x has a value of 1 and an address of 1000
  • y is 2 and the address is 1004
  • ip has value 1000 (address x ) and address 1008

Consider the following:

  • x == 1 and &x == 1000
  • y == 2 and &y == 1004
  • ip == 1000 and &ip == 1008 and *ip == 1 ( x value)

Hope this helps you understand what is happening.

+2
source share

All is correct.

1st line: you declare two variables

Second line: memory pointer "ip" defined

Third line: memory address X is assigned to the ip pointer

4th line: Y is now set to the value of the variable X at ip

The memory address, however, is in hexadecimal format. 011001110 is a data byte, not a memory address. The address will most likely be approximately 0x000000000022FE38 (it may be shorter). Consider this:

 int x = 0; int *ptr = &x; //the "&" character means "the address of" printf("The variable X is at 0x%p and has the value of %i", (void *)ptr, x); 

This will print the address of X, not * ptr. You will need another pointer to print the address * ptr. But this is pretty pointless since the pointer is defined to print the address of the variable. Think of it as an alias for another variable (this value is the value at this memory address).

0
source share

All Articles