d4_Pointers(指针)


 Pointers


     * Pointers are variables

     * Pointers store only address of the memory location.
       they do not store a value.

     * Pointers are declared like :-  int *ptr;

     * Address are always integer datatype , hence all  pointers need only 2 bytes


#include<stdio.h> void main() { int a=10; //Integer variable int *ptr; // Pointer variable ptr= &a; // address of a stored in ptr printf("%d\n",a); // prints value printf("%u\n",&a); // %u used to print address printf("%u\n",&ptr); //65526 printf("%u\n",ptr); // 65524 printf("%d\n",*ptr); //10 }

float类型:

#include<stdio.h>
void main()
{

       float b=10.24;    
       
       float * ptr; // 2bytes  float means the data type of the value present at this address

       ptr = &b;

       printf("%f\n",b);  //10.24
       printf("%u\n",&b);  // 65524
       printf("%u\n",ptr); // 65524
       printf("%u\n",&ptr); // 65528
       printf("%f\n",*ptr);  // 10.24
 
}

 * int a =10;               // a Hold the value
 * int *ptr=&a            // ptr holds the address of variable
 * int **ptr=& ptr      // ptr1 holds the address of a pointer variable

 

#include<stdio.h>
void main()
{
       int a=10;    
       int * ptr;    //single pointer    
       int ** ptr1;  //double pointer

       ptr= &a;
       ptr1= &ptr;


       printf("%d\n",a);   //10 
  
       printf("%u\n",ptr);   //65524  %u: 输出地址
       printf("%u\n",&ptr);  //65526
       printf("%u\n",*ptr);  // 10
 
       printf("%u\n",ptr1);  // 65526
       printf("%u\n",&ptr1); // 65528
       printf("%u\n",*ptr1); // 65524
       printf("%u\n",**ptr1); // 10 
}

Use of pointers:

#include<stdio.h>
void swap(int *x,int *z);

  void main()
  {
           int a=10, b=20;

            swap(&a,&b); //call by reference
  
            printf(" a = %d",a);
            printf(" b = %d",b);

  }

  void swap(int *x,int *z)
  {
          int temp;
          temp=*x;
          *x=*z;
          *z=temp;
  }

posted on 2014-07-24 11:37  @冰糖  阅读(128)  评论(0编辑  收藏  举报

导航