Pointers and arrays - why is this working?

I'm studying on my own using a book. I'm working my way through this chapter on pointers and I wanted to try something (testing is what learning is all about right? ^_^). Specifically, I wanted to modify this prog using a pointer to allow the user to specify a number. After compiling the prog works just like I wanted it to, but how is that possible?

Here's the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// pointertest1.cpp : Defines the entry point for the console application.
// ex6.2.1.cpp : Defines the entry point for the console application.
//pg 153 Chapter 6 c++ WF Overland

/********************************************** //original prog
****sort uses two algorithms to sort an array**
****from lowest to highest entry.**************
***********************************************
****this exercise is to change the code to***** //first exercise from book
****arrange from highest to lowest.************
***********************************************
****In this test, I wanted to see if I could*** //reminder of the test for me
**** get user input on how many elements*******
**** need to be sorted. This was a test of*****
**** my pointer knowledge.********************
**********************************************/



#include "stdafx.h"
#include <iostream>
using namespace std;

void define(int *p3);
void sort(int n);
void swap(int *p1, int *p2);
int a[10]; //this is where I'm not certain of y this works - only 10 positions!
int r; //used for user to define number of elements to be sorted

int main() {
	while (1){
	int i;
    define(&r);
	if (r == 0)
		break;
    for (i = 0; i < r; i++) {
        cout << "Enter array element #" << i << ": ";
        cin >> a[i];
    }
    sort(10);
    cout << "Here are all the array elements, sorted:" << endl;
    for (i = 0; i < r; i++)
        cout << a[i] << " " << endl;
	}
    return 0;
}


//Define function: defines number of elements to be sorted
//
void define(int *p) {
    cout << "Enter number of elements to sort (0 to exit): " << endl;
    cin >> r;
}

//Sort array function: sort array named a, having n
//elements.
//
void sort(int n) {
    int i, j, high;
	n = r;
    for (i = 0; i < n - 1; i++) {
        //This part of the loop finds the highest
        //element in the range i to n - 1; the index
        //is set to the variable names high.
        high = i;
        for (j = i + 1; j < n; j++)
            if (a[j] > a[high])  //shouldn't this have only 10 positions?
                high = j;
        //This part of the loop performs a swap if needed
        if (i != high)
            swap(&a[i], &a[high]);
    }
}

//Swap function.
//Swap the values pointed to by p1 and p2.
//
void swap(int *p1, int *p2) {
	int temp = *p1;
	*p1 = *p2;
	*p2 = temp;
}//end prog 


Thanks a bunch! Sorry if this is simple and I just missed it, I've read and reread this many times...
Last edited on
You haven't said exactly what about the way it works you don't understand, but there are a few oddities in there that i can see which may be causing confusion.

function define(int *p)
You take a pointer to an integer as a parameter, but do not do anything with that pointer in the function. Instead you use the global varaible r directly.

function sort(int n)
You are calling this with a hard-coded 10 for n, but then overwrite that with the global variable r (line 61).

arrays - general
There is no 'bounds checking' on arrays in C++, so although you declare int a[10], the compiler will let you try and access a[37] if you wish. What is happenign 'behing the sceens' is that an array is actualy a constant pointer of the type the array is of (int in this case), and indexing is done by pointer arithmetic.
So a is actulay an int pointer to a[0].
a[1] is a pointer to the address of a[0] + sizeof(int) bytes
a[2] is a pointer to the address of a[0] + 2 x sizeof(int) bytes
etc.
There is a bit more on pointer and arrays on the site tutorial http://www.cplusplus.com/doc/tutorial/pointers.html

Luck - ahthough technically speaking it is flawed - you are overwriting space that does not belong to "array a" - and in this case you have got away with it.
Here is a simple program to illustrate my point.
I have two other arrays C and B - these are initialised to zero's.
Variable r decides how many repateing values we write to array A.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
int c [50]={0};

int a[10]; 

int b[25]={0};

int r = 20; //increase this value to write more valuses to array A

int main() {
	
   
	int i;
    
    for (i = 0; i < r; i++) 
    {
        a[i]=1;
    }
 
    cout << "Here are all the array(s) elements" << endl;
    cout << "Array A" << endl;
    for (i = 0; i < r; i++)
        cout << a[i] << " ";

    cout << endl << endl;

    
    cout << "Array C" << endl;
    for (i = 0; i < 50; i++)
        cout << c[i] << " ";

    cout << endl << endl;

    cout << "Array B" << endl;
    for (i = 0; i < 25; i++)
        cout << b[i] << " ";

    
    cout << endl; 
    system("pause");
    


    return 0;
}


This is the output of the program when I stay WITHIN the bounds of array A (all values correct)

Array A
1 1 1 1 1 1 1 1 1 1

Array C
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

Array B
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Press any key to continue . . .

**Now here is what happens when I write 50 numbers to array A (well beyond it's bounds)**

Here are all the array(s) elements
Array A
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1

Array C
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 0 0

Array B
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Press any key to continue . . .


As you can see we have started to overwrite array C.
If we continue even further past the bounds of array A we will completely overwrite C and possibly even B

@ Faldrax - thanks for the reply. The code itself has comments next to what I didn't understand. I wanted to use a pointer on a global variable to change the value of the variable. I know this is unnecessary with this little prog but I just wanted to test it. It does make more sense now though; I didn't know/understand that array parameters aren't verified. Also I didn't realize until now that i wrote define(int *p) and not define(int *p3) - so obviously I need to spend some more time studying...

@ guestgulkin - thanks also. Your explanation does clear it up even more.

Thanks guys - I thought I was cleaver when it worked, but I knew something was wrong. I tried to think it through before I posted - I don't want to waste anyone's time. Thanks again! ^_^
Topic archived. No new replies allowed.