Various C++ Examples (including IPC)  Version: 1.0.0
iteration.cc File Reference

Program that demonstrates various iteration constructs. More...

#include <iostream>
#include <cstring>
Include dependency graph for iteration.cc:

Go to the source code of this file.

Macros

#define MAX   10
 

Functions

int main (int argc, char **argv)
 

Detailed Description

Program that demonstrates various iteration constructs.

Definition in file iteration.cc.

Macro Definition Documentation

#define MAX   10

Definition at line 9 of file iteration.cc.

Referenced by main().

Function Documentation

int main ( int  argc,
char **  argv 
)

Definition at line 11 of file iteration.cc.

References MAX.

12 {
13  int i, j;
14 
15  for(i=0, j=0; i < MAX; i++)
16  {
17  cout << "IN LOOP:i=" << i << endl;
18  cout << "IN LOOP:j=" << j << endl;
19  ++j;
20  }
21 
22  cout << "AFTER LOOP:i=" << i << endl;
23  cout << "AFTER LOOP:j=" << j << endl;
24 
26 
27  //array copying using pointers.
28  char s1[MAX] = "012345678";
29  char s2[MAX];
30 
31  //set the contents of s2 to all '\0' characters.
32  memset(s2, 0, MAX);
33 
34  char *p1 = s1, *p2 = s2;
35 
36  //copy the contents of one array into another using pointers.
37  while(*p2++ = *p1++);
38  cout << "s2=" << s2 << endl;
39 
40  //reset the contents of s2 to "null" characters
41  memset(s2, 0, MAX);
42 
43  //put something into the first element of s2 so we will be able to
44  //print it later on (otherwise a '\0' character is sitting in there
45  //from the memset we just did).
46  s2[0] = '9';
47 
48  //reset the pointers to point to be beginning of each array
49  //respectively.
50  p1 = s1, p2 = s2;
51 
52  //copy from the second element of s1 thru to the last element of s1
53  //(including terminating 0) into the second element of s2 thru the
54  //last element of s2.
55  while(*++p2 = *++p1);
56  cout << "s2=" << s2 << endl;
57 
58 
59  //ERROR
60  /* This is a programming error. We copy the contents of p1 from the
61  first to the last element (MAX size) including the null terminator
62  (\0) but the size of the array (s2) that p2 points to is only MAX
63  length. The issue here is that we are starting our copy from the
64  second element of s2 (s2[1]) and copying MAX more characters into
65  the contiguious space respectively.
66 
67  Due to boundry lines on most modern computers this will most likely
68  not produce a runtime error unless resources are low. At any rate we
69  are "poking" a char into a memory address that is not managed my our
70  program. One way of fixing this problem might be to increase the
71  size of the array s2 or provide some sort of range checking.
72  */
73  while(*++p2 = *p1++);
74  cout << "s2=" << s2 << endl;
75 
76  cout << "sizeof(s2)="<<sizeof(s2)<<endl;
77  cout << "sizeof(p2)="<<sizeof(p2)<<endl;
78 
79  return 0;
80 }
#define MAX
Definition: iteration.cc:9