/* Program to demonstrate pointers (integers) Version 1.0 / 2001.09.01. Peter Schindler pstrainer@gmx.net */ #include #include #include /* Declaration of globals ***********************************/ void suba (int m); void subb (int *pm); // *pm is a pointer to int /* Main program *********************************************/ void main (void){ int i,j,k; // integer variables int *pi; // pointer to int variable printf("Pointer Test Program\n"); printf("Enter integer number: "); scanf("%d",&i); printf("\n"); // set pointer pi to the address of i ("let it point at i") pi=&i; /* assign other variables in different ways */ j=i; // set j to value of i k=*pi; // set k to value of whatever pi points at /* send VALUE to subroutine */ printf("main01 i=%d j=%d k=%d pi=%d\n",i,j,k,pi); suba(i); // i remains unchanged printf("main02 i=%d j=%d k=%d pi=%d\n\n",i,j,k,pi); /* send POINTER to subroutine */ printf("main03 i=%d j=%d k=%d pi=%d\n",i,j,k,pi); subb(pi); // i can be changed printf("main04 i=%d j=%d k=%d pi=%d\n\n",i,j,k,pi); printf("End of program\n"); _getch(); } /* suba: get integer value and change it ******************* You may change local variable, without effect to main */ void suba (int m) { int n; n=m; printf("suba01 m=%d n=%d\n",m,n); m++; /* change local variable */ printf("suba02 m=%d n=%d\n",m,n); } /* suba: get pointer value, change value ******************* You may change local variable but also main ! */ void subb (int *pm) { int m,n; m=*pm; /* set m to whatever pm points at */ n=m; printf("subb01 m=%d n=%d pm=%d\n",m,n,pm); m++; /* change local variable */ *pm=m; /* set whatever pm points at to m */ printf("subb02 m=%d n=%d pm=%d\n",m,n,pm); } /* eof ******************************************************/