• R/O
  • SSH

Tags
No Tags

Frequently used words (click to add to your profile)

javac++androidlinuxc#windowsobjective-ccocoa誰得qtpythonphprubygameguibathyscaphec計画中(planning stage)翻訳omegatframeworktwitterdomtestvb.netdirectxゲームエンジンbtronarduinopreviewer

File Info

Rev. 13bbe14cddfbb4e8ecabf84c37906a48d7159fd6
Size 2,011 bytes
Time 2008-10-21 02:02:25
Author iselllo
Log Message

An example taken from the C book that allows me to swap two numbers in C.

Content

#include <stdio.h>

void swap_wrong(int x, int y)
{
  int temp;
  temp=x;
  x=y;
  y=temp;

}

/* Some comments: the following function takes two pointers as arguments. Or better: 
the argument ip is defined as a pointer to an integer variable. 


From the C book:
The idea is that the the parameters are declared to be pointers inside the function itself and
then the calling program passes pointers to the values to be changed.


The pointers are generated in the calling program directly from the variables using the
referencing operator "&".


See pages 95 and following of the C book.


    */


void swap_right(int *px, int *py)
{
  int temp;

  temp= *px;  /* store in temp [plain integer variable] the value the integer pointer px
   points at   */
  
  *px= *py;   /* read the value stored in the memory location the pointer py points at and copy
	       that value in the memory location the pointer px points at.*/

  *py= temp;  /* store the value of them in the memory location the pointer py points at  */

/* Moral of the story: there are the integer variables x and y and their pointers px and py.
The variables x and y are stored somewhere in memory.
 The function swaps_right accesses the locations where a and b are stored and their values via the 
pointers to x and y. It then swaps the values stored at the memory locations corresponding
to a and b. The net result is that the function can change the values of the variables x and y     */

}


main()
{
  int a;
  int b;


  a=10;
  b=20;



  swap_wrong(a,b);

  printf("before swapping \n");

  
  printf("a is\n");
  printf("%d\n ", a);        

  printf("b is\n");

  printf("%d\n ", b);        

  printf("after swapping without pointers \n");

  
  printf("a is\n");
  printf("%d\n ", a);        

  printf("b is\n");

  printf("%d\n ", b);        


  swap_right(&a,&b);


  printf("after swapping USING pointers \n");

  
  printf("a is\n");
  printf("%d\n ", a);        

  printf("b is\n");

  printf("%d\n ", b);        

  

}