C Tutorial/Pointer/Address and Pointers

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Address and Pointers

Address

  1. Each variable has two attributes: address and value.
  2. The address is the location in memory.
  3. In that locaton, the value is stored.
  4. During the lifetime of the variable, the address is not changed but the value may change.

Pointers

  1. A pointer is a variable whose value is an address.
  2. A pointer to an integer is a variable that can store the address of that integer.

10.2.Address and Pointers 10.2.1. Address and Pointers 10.2.2. <A href="/Tutorial/C/0200__Pointer/UsingPointers.htm">Using Pointers</a> 10.2.3. <A href="/Tutorial/C/0200__Pointer/Printaddressesusingplaceholders16luorp.htm">Print addresses using place holders %16lu or %p.</a>

Print addresses using place holders %16lu or %p.

#include <stdio.h>
main()
{
    int a[5];
    int i;
    for(i = 0;i<5;i++)
    {
        a[i]=i;
    }
    for(i = 0;i<5;i++)
    {
        printf("value in array %d and address is %16lu\n",a[i],&a[i]);
    }
   for(i = 0;i<5;i++)
    {
        printf("value in array %d and address is %p\n",a[i],&a[i]);
    }
}
value in array 0 and address is           631656
      value in array 1 and address is           631660
      value in array 2 and address is           631664
      value in array 3 and address is           631668
      value in array 4 and address is           631672
      value in array 0 and address is 9a368
      value in array 1 and address is 9a36c
      value in array 2 and address is 9a370
      value in array 3 and address is 9a374
      value in array 4 and address is 9a378

Using Pointers

Define a pointer: include a * before the name of the variable.

Get the address: use &.


#include <stdio.h>
main ()
{
   int i;        
   int * ia;     
   i = 10;       
   ia = &i;  
    printf (" The address of i is %8u \n", ia);         
    printf (" The value at that location is %d\n", i);  
    printf (" The value at that location is %d\n", *ia);
    *ia = 50;                               
    printf ("The value of i is %d\n", i);              
}
The address of i is   631672
 The value at that location is 10
 The value at that location is 10
The value of i is 50