Explain Arrays Please

Pages: 12345... 9
It give this error when i try to compile, i changed the file paths correctly i think.

C:\CSC 2100\Program Two>g++ God.cpp -o a
God.cpp: In function 'int actionOnSpace()':
God.cpp:221:41: error: no matching function for call to 'std::basic_fstream<char
>::open(std::string&, const openmode&)'
God.cpp:221:41: note: candidate is:
In file included from God.cpp:5:0:
c:\mingw\bin\../lib/gcc/mingw32/4.7.2/include/c++/fstream:871:7: note: void std:
:basic_fstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [wit
h _CharT = char; _Traits = std::char_traits<char>; std::ios_base::openmode = std
::_Ios_Openmode]
c:\mingw\bin\../lib/gcc/mingw32/4.7.2/include/c++/fstream:871:7: note: no know
n conversion for argument 1 from 'std::string {aka std::basic_string<char>}' to
'const char*'

C:\CSC 2100\Program Two>

this must be a gcc thing, compiles fine here under VS2013.

try changing this line in function actionSpace()

From:
1
2
	// attempt to open file
	externalFile.open(fileName, fstream::in);

To:
1
2
	// attempt to open file
	externalFile.open(fileName.c_str(), fstream::in);

That fixed it thank you, let the studying begin!

Great :)
Aright i got everything working except when someone hits position 25 the game doesn't end it wont jump out of that loop, just keeps going and going.


edit: found problem didn't ever set the gamePlaying variable to false once someone hit 25.
Last edited on

Lovely, all part of learning :)
the evil class has struck again with the dreaded arrays but now with pointers included, how can a single *array be used in functions to calculate mean median and mode?
I suppose the first question is.. forgetting cpp, do you know how to calculate Mean, Median and Mode? - it would help :)
Yes i do :p
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
float getMean(const int values[] , int num){
    if (num<=0) return 0;
    int count=0;
    for (int i=0;i<num;i++) count += values[i];
    return (float)count / num;
}

float getMedian(const int values[],int num){
    if(num<=0) return 0;
    if(num%2) return (float)values[(num+1)/2];
    else{
        int pos = num/2;
        return (float)(values[pos] + values[pos+1]) / 2;
    }
}

int getMode(const int values[],int num){
    if(num<=0)return 0;
    int max_count=0 , pos=0, max_nums=0;
    int count=1;
    for(int i=1;i<num;i++){
        if(values[i] != values[pos]){
            if(count > max_count){
                max_count=count;
                max_nums=0;
            }else if (count == max_count) max_nums++;
            pos= i;
            count=0;
        }else count++;
    }
    if(max_nums) return 0;
    else return values[pos];
}


these funtions do what they need to but i dont understand the whole pointers part.


It also does not help that the directions for this program are very vague
Last edited on
These are the function so far, with my blind attempts to insert the pointers into them, there are three other functions other than this on is to print out the array thats pointed to(think i did this one right), one is to gather the numbers to be sorted and relate them to the "size" of the survey pool, and the other is meant to create an array(think the one that im pointing to in all of these if im not mistaken) equal to the "size" (think this is just like the "initalizearrays" function in last project). This whole "pass by reference doesnt make sence, is it like setting two arrays equal to each other so that one array with numbers can associate another array that just holds names?
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

double getAverage(double *array[], int hours) 
{
    double dSum = *array[0];
    for (int i = 1; i < hours; ++i) {
        dSum += *array[i];
    }
    return dSum
}

int getMode(int *array, int hours)
{
	int *repetitions;
	int highest, element;
	
	repetitions = new int[hours];
	for(int x=0; x<hours; x++)
		*(repetitions+x) = 0;
		
	for(int x=0; x<hours; x++)
	{
		for(int y=0; y<hours; y++)
		{
			if(*(array+x) == *(array+y))
				*(repetitions+x)++;
		}
	}
	highest = *(repetitions+0);
	for(int x=1; x<hours; x++)
	{
		if(*(repetitions+x) > highest)
		{
			highest = *(repetitions+x);
			element = x;
		}
	}
	if(highest == 1)
		return -1;
	else
		return *(array+element);
} 

double getMedian(double *array[], int size)
{
    if(size<=0) return 0;
    if(size%2) return (float)*array[(size+1)/2];
    else{
        int pos = size/2;
        return (float)(*array[pos] + *array[pos+1]) / 2;
    }
}

void selectionSort(float *array, int size)
{
	int startScan, minIndex;
	float minValue;

	for (startScan = 0; startScan < (size - 1); startScan++)
	{
		minIndex = startScan;
		minValue = *(array+startScan);
		for(int index = startScan + 1; index < size; index++)
		{
			if (*(array+index) < minValue)
			{
				minValue = *(array+index);
				minIndex = index;
			}
		}
		*(array+minIndex) = *(array+startScan);
		*(array+startScan) = minValue;
	}
}

Yes i do :p

lol, never doubted you for a second :p

It also does not help that the directions for this program are very vague

Post the directions so I can have a look then I can help you better.

Anyway, on the note of "Pass By Reference", i have provided a little example below (with comments).. if your still unsure just ask.

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

#include <iostream>
#include <cctype>		// toupper
using namespace std;

// global const for testing
const int ARRAY_SIZE = 34;

// function prototype
void referenceFunction(char someArray[]);

int main()
{

	// delare a local variable (so in lamers terms my
	// referenceFunction() function wont be able to see
	// this or modify it unless I pass it as a reference
	// to my function)

	// take note that my referenceFunction is not returning
	// any values but simply updating the below array that
	// i passed to it.

	char myArray[ARRAY_SIZE] = "c++ is a great language to learn!";

	// pass our myArray as a reference to my function and
	// let the function modify it by making all the letters
	// uppercase  :)

	referenceFunction(myArray);

	// lets check we have updated the array
	for (int i = 0; i < ARRAY_SIZE; i++)
		cout << myArray[i];
	
	return 0;
}

// example function to receive reference to array, notice
// we are not returning any value and its simply void.
void referenceFunction(char someArray[])
{
	for (int i = 0; i < ARRAY_SIZE; i++)
		someArray[i] = toupper(someArray[i]);
}



Another example I did for another board member passing by reference:
http://www.cplusplus.com/forum/beginner/126006/


A pointer version....


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

#include <iostream>
#include <cctype>		// toupper
using namespace std;

// function prototype
void referenceFunction(char *myArrayPointer);

// global const for testing
const int ARRAY_SIZE = 34;


int main()
{

	// ive declared a local variable called myArray and normally
	// local variables can only be seen or accessed by the function
	// it is declared in.

	char myArray[ARRAY_SIZE] = "c++ is a great language to learn!";

	// we are going to pass the array to our function, and since the 
	// param is a pointer we are passing the pointer (address to the 
	// first element of the array)

	// arrays dont keep track of their size so I have merely created 
	// a constant globally. However, it can be done where you pass the
	// size to the function instead.. something like..

	// void referenceFunction(char *myArrayPointer, int size);

	referenceFunction(myArray);

	// lets check we have updated the array
	for (int i = 0; i < ARRAY_SIZE; i++)
		cout << myArray[i];


	return 0;
}

// 
//	$function:	Accepted a pointer to my array and make it uppercase
//
void referenceFunction(char *myArrayPointer)
{
	// It good practice to ensure parameters passed by address
	// are not null pointers. Dereferencing a null pointer usually
	// would cause your program to crash  ;-)

	if (!myArrayPointer)
		return;			// get me out of ere!

	for (int i = 0; i < ARRAY_SIZE; i++)
		myArrayPointer[i] = toupper(myArrayPointer[i]);
}
https://www.dropbox.com/sh/59lwg1a228gom47/GL3caYyR0W this has my code for the project which i finished all parts last night but riddled with misunderstandings and errors, and the project pdf :)

Did my examples above make any sense to you?
Last edited on
Just woke up :p saw first part of post on my phone(code doesnt show well on phone) so i sent what i have, out eating breakfast now so ill go all sherlock holms on it when i get back. Thank you again
Yes i think i do, how do you mark multiple arrays to be used as pointers or would i only need to use one array and clear the information in it each time?
also this has informed me that you can have just one variable in the function header, i though it was possible just didn't feel confident enough to act on it.

Not sure what you mean about multiple arrays or just needing one and clearing it each time?

The way the assignment reads is that you ask for number of students who were surveyed, use that number to allocate a array of the correct size dynamically in makeArray(). That array is then used by each function so it wouldn't need to be cleared.

In my pointer example I used array notation ( using the [i] ) so when you write yours you would need to use the pointer notation, i.e. *(array+offset) like the method used in the selectSort function.

Anyway, wrote this quickly before I head off to bed as I'm shattered lol, been a long day today... dam bugs in my Android app!

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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100

#include <iostream>
using namespace std;

// function prototype
float* makeArray(int size);
void getFBData(float *data, int size);
void selectionSort(float *array, int size);

int main()
{	
	float *studentData;
	int numStudents;

	cout << "How many students were surveyed? ";
	cin >> numStudents;
	
	// allocate some space for our students and return 
	// a pointer to our array in studentData.
	studentData = makeArray(numStudents);

	if (studentData == nullptr)
		cout << "Error allocating memory.";
	else
	{
		// we have our memory allocated, call getFBData
		// to read in the student information.
		getFBData(studentData, numStudents);

		// call get average (4)
		selectionSort(studentData, numStudents);	// (5)
		// call print array (6)
		// call getMedian (7)
		// call getMode (8)
		// do (9)


		// **** For Debug:  check we have the details ok
		for (int i = 0; i < numStudents; i++)
			cout << *(studentData + i) << endl;

		// im finished, free the memory allocated
		delete[] studentData;
	}

	return 0;
}

//
//	$function:	Allocate memory as per the number of students surveyed.
//	$returns:	Returns pointer to allocated memory.
//
float* makeArray(int size)
{
	float *data = new float[size];
	return data;
}

//
//	$function:	Read in x number of students hours.
//
void getFBData(float *data, int size)
{
	float myNum;
	for (int i = 0; i < size; i++)
	{
		do
		{	
			cout << "Enter hours for student " << i + 1 << ": ";
			cin >> myNum;
			*(data + i) = myNum;
		} while (myNum < 0);	// loop if we are a minus number
	}
}

//
//	$function:	Sort array.
//
void selectionSort(float *array, int size)
{
	int startScan, minIndex;
	float minValue;

	for (startScan = 0; startScan < (size - 1); startScan++)
	{
		minIndex = startScan;
		minValue = *(array + startScan);
		for (int index = startScan + 1; index < size; index++)
		{
			if (*(array + index) < minValue)
			{
				minValue = *(array + index);
				minIndex = index;
			}
		}
		*(array + minIndex) = *(array + startScan);
		*(array + startScan) = minValue;
	}
}
Alright I looked at what you showed me up there and make alot of changes and fixed my getAverage function(that took forever turns out i deferenced it in the function definition). I however cant figure 3 errors im getting when i try to compile it



main.cpp: In function 'int main()':
main.cpp:20:28: error: 'array' was not declared in this scope
main.cpp:20:36: error: 'hours' was not declared in this scope
main.cpp:28:22: error: 'nullptr' was not declared in this scope

I have no idea how to fix these I've been trying all night. here's my zombie int main.

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
int main()
{
	float *studentData;
	int numStudents;
	int size;
	int average = getAverage(*array, *hours);
	int median = getMedian(hours);
	int mode = getMode(hours);

	cout << "How many students were surveyed?  ";
	cin >> numStudents;
	studentData = makeArray(numStudents);

	 if (studentData == nullptr)
		 cout << "Error allocating memory.";
	 else
	 {
		 getFBData(studentData, numStudents);
		 selectionSort(studentData, numStudents);

		 for (int i = 0; i < numStudents; i++)
			 cout << *(studentData + i) << endl;

		 delete[] studentData;
	 }
	 
	 getAverage(*array, hours);
	 printArray(size, hours);
	 getMedian(*array, hours);
	 getMode(*array, hours);

	cout << "STATISTICS FOR TIME SPENT ON FACEBOOK & TWITTER" << endl;
	cout << "\n  Mean: " << average;
	cout << "\n  Median: " << median;
	cout << "\n  Mode: " << mode;


	return 0;
}


Edit: i fixed the nullptr issue, apparently my compiler doesnt like it so i just replaced it with '0'. now i just have those other two errors and have no idea how to fix them.
Last edited on

Assuming your makeArray was like my example then studentData should be a pointer to your array of size numStudents, therefore your function calls should be referencing that and not *array.

I also noticed in line 6 - 8 you reference *array in the calling functions but you haven't allocated the memory which stores the student hours. Remember the data would be in studentData which at that point hasn't been allocated or populated yet.

Because studentData is already a pointer to allocated memory, you don't need the * when passing it to the functions like you have with *array in your example, i.e. check what I did with getFBData where I passed the pointer held in studentData.

On the note of *array, not sure where that is declared or what it actually is.

So as an example, the getAverage function should reference your studentData, calculate the average and return it back to the main as detailed in the getAverage function in the pdf. i.e.

float getAverage(float *data, int size);

so in your main you would need a variable to return the result in like..
averageResult = getAverage(studentData, numStudents);

averageResult would then hold the average of your dynamically allocated array.

So, basically in my example (just so you get an idea of whats going on)..

* I create a pointer variable called studentData in main().
* I ask how many students we surveyed and stored in numStudents
* I called makeArray which dynamically allocated some memory of size numStudents and returned the pointer to that memory (address in memory) that is stored in studentData.
studentData = makeArray(numStudents);
* I then call getFBData to loop numStudent number of times and ask for student number of hours, and each time storing it in the allocated studentData.
* I then do a sort using the function provided.
Ive Turned this into a total mess with these pointers, every time i fix an error i gt 3 more to replace it. I'm pretty sure I've ruined three of my functions but trying to use pointers. I think I've gotten myself all confused on what i need to pass down to the functions now so they can do the math they need to.

Here's my code
Here's the errors that I cant figure out.

Edit: i fixed the error:'hours' by updating that to 'studentData'
the reason i used *array which is the second error is because the function the teacher provided uses it and i have no idea what that function does, she didn't even bother to explain it in class. my best guess is it arranges numbers from least to greatest. what should i replace '*array' with inorder to get this to at least compile?


C:\CSC 2100\Program Three>g++ main.cpp
main.cpp: In function 'int main()':
main.cpp:40:13: error: 'array' was not declared in this scope
main.cpp:41:18: error: 'hours' was not declared in this scope
main.cpp: At global scope:
main.cpp:89:1: error: expected unqualified-id before '{' token

C:\CSC 2100\Program Three>

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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
#include <iostream>
#include <iomanip>

using namespace std;

float* makeArray(int);
void getFBData(float* , int);
void selectionSort(float*, int);
void printArray(int, float*);
float getAverage(float*, int);
int getMode(int, float*);
double getMedian(double, int);

int main()
{
	float *studentData;
	int numStudents;
	int size, mode;
	double average, median;
	
	cout << "How many students were surveyed?  ";
	cin >> numStudents;
	studentData = makeArray(numStudents);

	 if (studentData == 0)
		 cout << "Error allocating memory.";
	 else
	 {
		 getFBData(studentData, numStudents);
		 selectionSort(studentData, numStudents);

		 for (int i = 0; i < numStudents; i++)
			 cout << *(studentData + i) << endl;

		 delete[] studentData;
	 }
	 
	getAverage(studentData, numStudents);
	printArray(size, studentData);
	getMedian(*array, studentData);
	getMode(*array, studentData);

	average = getAverage(studentData, numStudents);
	median = getMedian(*array, studentData);
	mode = getMode(*array, studentData);
	cout << "STATISTICS FOR TIME SPENT ON FACEBOOK & TWITTER" << endl;
	cout << "\n  Mean: " << average;
	cout << "\n  Median: " << median;
	cout << "\n  Mode: " << mode;


	return 0;
}


float* makeArray(int size)
{
	float *data = new float[size];
	return data;
}


void getFBData(float *data, int size)
{
	float myNum;
	for (int i = 0; i < size; i++)
	{
		do
		{
			cout << "Enter hours for student " << i + 1 << ": ";
			cin >> myNum;
			*(data + i) = myNum;
		} while (myNum < 0);	
	}
}

void printArray(int size, float *data)
{
	int x = *data;
	cout << "Number of hours each student spent on Facebook / Twitter in ascending order : " << endl;

	for (x = 0; x <= size; x++)
	{
		cout << x << "  " << endl;
	}
}

float getAverage(float *data, int *num);
{
	int *average = new int((num) / data);

	return *average;
}

int getMode(int *array, float *data)
{
	int *repetitions;
	int highest, element, i;
	*data = i;

	repetitions = new int[i];
	for (int x = 0; x<i; x++)
		*(repetitions + x) = 0;

	for (int x = 0; x<i; x++)
	{
		for (int y = 0; y<i; y++)
		{
			if (*(array + x) == *(array + y))
			{
				(*(repetitions + x))++;
			}
		}
	}
	highest = *(repetitions + 0);
	for (int x = 1; x<i; x++)
	{
		if (*(repetitions + x) > highest)
		{
			highest = *(repetitions + x);
			element = x;
		}
	}
	if (highest == 1)
		return -1;
	else
		return *(array + element);
}

double getMedian(double *array, int *hours)
{
	if (*hours <= 0) return 0;
	if (*hours % 2) return (float)array[(*hours + 1) / 2];
	else{
		int pos = *hours / 2;
		return (float)(array[pos] + (array[pos + 1]) / 2);
	}
}

void selectionSort(float *array, int size)
{
	int startScan, minIndex;
	float minValue;

	for (startScan = 0; startScan < (size - 1); startScan++)
	{
		minIndex = startScan;
		minValue = *(array + startScan);
		for (int index = startScan + 1; index < size; index++)
		{
			if (*(array + index) < minValue)
			{
				minValue = *(array + index);
				minIndex = index;
			}
		}
		*(array + minIndex) = *(array + startScan);
		*(array + startScan) = minValue;
	}
}
Pages: 12345... 9