• R/O
  • SSH

Commit

Tags
Aucun tag

Frequently used words (click to add to your profile)

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

Commit MetaInfo

Révision13bbe14cddfbb4e8ecabf84c37906a48d7159fd6 (tree)
l'heure2008-10-21 02:02:25
Auteuriselllo
Commiteriselllo

Message de Log

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

Change Summary

Modification

diff -r 9209b2e13fe8 -r 13bbe14cddfb C-codes/swap_test.c
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/C-codes/swap_test.c Mon Oct 20 17:02:25 2008 +0000
@@ -0,0 +1,101 @@
1+#include <stdio.h>
2+
3+void swap_wrong(int x, int y)
4+{
5+ int temp;
6+ temp=x;
7+ x=y;
8+ y=temp;
9+
10+}
11+
12+/* Some comments: the following function takes two pointers as arguments. Or better:
13+the argument ip is defined as a pointer to an integer variable.
14+
15+
16+From the C book:
17+The idea is that the the parameters are declared to be pointers inside the function itself and
18+then the calling program passes pointers to the values to be changed.
19+
20+
21+The pointers are generated in the calling program directly from the variables using the
22+referencing operator "&".
23+
24+
25+See pages 95 and following of the C book.
26+
27+
28+ */
29+
30+
31+void swap_right(int *px, int *py)
32+{
33+ int temp;
34+
35+ temp= *px; /* store in temp [plain integer variable] the value the integer pointer px
36+ points at */
37+
38+ *px= *py; /* read the value stored in the memory location the pointer py points at and copy
39+ that value in the memory location the pointer px points at.*/
40+
41+ *py= temp; /* store the value of them in the memory location the pointer py points at */
42+
43+/* Moral of the story: there are the integer variables x and y and their pointers px and py.
44+The variables x and y are stored somewhere in memory.
45+ The function swaps_right accesses the locations where a and b are stored and their values via the
46+pointers to x and y. It then swaps the values stored at the memory locations corresponding
47+to a and b. The net result is that the function can change the values of the variables x and y */
48+
49+}
50+
51+
52+main()
53+{
54+ int a;
55+ int b;
56+
57+
58+ a=10;
59+ b=20;
60+
61+
62+
63+ swap_wrong(a,b);
64+
65+ printf("before swapping \n");
66+
67+
68+ printf("a is\n");
69+ printf("%d\n ", a);
70+
71+ printf("b is\n");
72+
73+ printf("%d\n ", b);
74+
75+ printf("after swapping without pointers \n");
76+
77+
78+ printf("a is\n");
79+ printf("%d\n ", a);
80+
81+ printf("b is\n");
82+
83+ printf("%d\n ", b);
84+
85+
86+ swap_right(&a,&b);
87+
88+
89+ printf("after swapping USING pointers \n");
90+
91+
92+ printf("a is\n");
93+ printf("%d\n ", a);
94+
95+ printf("b is\n");
96+
97+ printf("%d\n ", b);
98+
99+
100+
101+}