How to resize an array?

Pages: 12
Hello, I'm trying to code this little thing, don't ask about what it is or efficiency, I'm just trying to work a little with C++, and what I'm trying to do is get the USER to initialize the length of an array. I don't want to make it myself. Is this possible to do?

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
#include <iostream> //"includes" the input and output streams of the input/output stream library. This is a LIBRARY.
#include <cstdlib> //"includes" all of the standard library of the C language library. 
#include <string>
#include <vector>>
using namespace std; //uses all instances of the "std" class.


 //creates a string array names[] with 10 values.
int average;
int amountOfGrades; //creates an integer called amountOfGrades.
int amountOfStudents; //creates an interger called amountOfStudents.
int grades[1];
int averageArray[1][1];
string names[1];
//All functions that are not void return something. The main function should usually be void. VOID means the function does NOT return a value.

/*These four are creating FUNCTION PROTOTYPES. This is because every C++ program requires a "main" function.
*This program does include one, but in order for the compiler to recognize these functions and
*call them in the main function, they must be "announced" earlier in the program, or coded before
*the main function. Either way is okay with the compiler.*/

int getInt()
{
	int x;
	cin >> x;
	return x;
}

double getDouble()
{
	double x;
	cin >> x;
	return x;
}
char getChar()
{
	char x;
	cin >> x;
	return x;
}
string getString()
{
	string x;
	cin >> x;
	return x;
}

void calcAverage(int array[],string array2[], int students, int grades)
{
	int average;
	for(int i = 0; i<students; i++)
	{
		for(int j = 0; j<grades; j++)
			averageArray[i][j] = array[i],array2[j];
	}
}
void printAverages(int array[],string array2[], int students, int grades)
{
	for(int i = 0; i<students; i++)
	{
		cout<<array2[i]<<" has grades of:"<<endl;
		
		for(int j=0; j<grades; j++)
			cout<<array[j]<<", ";
	}
}

int main()
{ //Braces always start functions, loops, conditions, etc
	
		cout << "Enter the amount of grades you'd like to enter.\n"; //cout stands for "console output". It outputs a line from the console to the user.
		amountOfGrades = getInt(); //the amount variable is being set to the function getInt(x) with the parameter x. It calls to that function. Explained below.
		cout << "Enter the amount of students you're going to have." << endl;
		amountOfStudents = getInt();
		for (int i = 0; i < amountOfStudents; i++) //begins a for loop. A for loop has the initializer, when the loop starts, creates the "end-er", what ends the loop, and then the incrementer.
			//This for loop starts an integer count at zero, a LOCAL VARIABLE, i to zero. The loop ends when i is less than the variable 'amountOfStudents', and it increments the variable 'i' by one everytime the loop finishes.
		{
			cout << "Enter the name of the student."; //prints the line telling the user to enter a string of the students name.
			names[i] = getString(); //sets the array names of POSITION [i] (same one in the for loop) to equal whatever the user inputs into the getString(x) function. It's a function CALL.

			for (int j = 0; j < amountOfGrades; j++)
			{ //creates another for loop, with j as the starter, j less than the amountOfGrades, and increments j by 1 everytime the loop restarts.
				cout << "Enter the grade." << endl; //tells the user to enter a grade. endl ends the line.
				grades[j] = getDouble(); //sets the array grades of POSITION[j] to the function getDouble().
			}
		}
	calcAverage(grades, names, amountOfStudents, amountOfGrades);
	printAverages(grades, names, amountOfStudents, amountOfGrades);
		
			
	system("Pause"); //pauses the system. Just utilize this
	return 0;
}
For that you need a dynamic array int *arr = new int[SIZE];
Arrays can't be resized. Instead, consider using a C++ container like std::vector, as it will resize for you:
http://www.cplusplus.com/reference/vector/vector/
http://en.cppreference.com/w/cpp/container/vector
Normally you should learn about std::vector before learning about plain arrays.

Use of the new keyword is discouraged in modern C++.
Last edited on
Or you may want to have a look at the following lines of code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void tst(const size_t size)    // Don't try to modify `size´
{
    static const string SEP(" ");

    int ar[size];    // Dynamically create an array of given `size´

    // Fill `ar´ with values
    int v = 0;
    for (int &item : ar)
    {
        item = v++;
    }

    // Print `ar´
    for (int item : ar)
    {
        cout << item << SEP;
    }
    cout << endl;

} /* tst() */
The best way would be to use a standard container (f.e. std::vector) from STL template library.
tcs wrote:
1
2
3
4
5
void tst(const size_t size)    // Don't try to modify `size´
{
    static const string SEP(" ");

    int ar[size];    // Dynamically create an array of given `size´ 
That is not valid C++.
Last edited on
closed account (48T7M4Gy)
Use of the new keyword is discouraged in modern C++. 


That's a new one. Can we have an authoritative reference for that please.
It's not new. RAII has been around for ages. Use it.

The STL makes life easier in the simplest sense as well with make_shared and make_unique. There isn't a whole lot of reason to be using new and delete directly in production code.
closed account (48T7M4Gy)
There isn't a whole lot of reason to be using new and delete directly in production code.


The OP is about dynamic arrays not the same ol boring stuff that goes on here about vectors or any other STL component being better. We all know that.

So far, beyond some sort of un-authoritative opinion there is obviously no reason whatsoever to take any notice of silly comments on discouraging the use of new and delete. Maybe we should discourage the use of printers because they have the associated problem of running out of ink, or avoid the use of monitors because they are subject to power failures and because pen and paper are more reliable.

Let's hear an authoritative comment on why new and delete are discouraged, even worse in production code. Call me old-fashioned but somehow I don't think pointers are going away.
How about Herb Sutter?
http://herbsutter.com/2013/05/29/gotw-89-solution-smart-pointers/
http://herbsutter.com/elements-of-modern-c-style/
http://herbsutter.com/gotw/_102/

Pointers aren't going away. Playing memory manager is.

When you play your own memory manager, you've got to watch out for:
- exceptions
- the big five
- scope
- circular dependencies
- container classes

When you use something that handles all the nasty details for you, like std::vector or std::list, then you eliminate all the stupid errors you are guaranteed to make.

I'm sure LB or Disch or JLBorges can provide a much better answer than I.
closed account (48T7M4Gy)
Yawn - and none of that esoterica adds value to the question raised by OP.
You're the one who jumped in and derailed the thread with the "new" stuff!

So if you're just trolling me, I'm done. Bye!
The OP is about dynamic arrays

No. IMO the OP is about a data structure that can hold the grades, where the number of grades (and students) is revealed during runtime.

Judging by the OP code any simple to use solution is strongly preferable, and std::vector is such. Granted, one has to learn to use the vector, but that is really easy (and useful skill too) compared to writing a low-level memory management properly.


There is no such thing as plain new int [size];. If you want to learn new, you have to learn that every new must have matching delete and that gets complicated really quickly. The easiest way is to ensure the delete is to encapsulate the memory management in a class. That is RAII. However, then you should master classes too (and the big five and ...).

Do you know how to craft a wheel for a car? I don't, but I use them happily.
Do I know how many lines of code is in the implementation of std::vector? No, but I use it happily.
I have some old code that uses an array of my own. It scares me.

give a man a fish and you feed him for a day; teach a man to fish and you feed him for a lifetime

You can argue that the std::vector is a mere fish, but the Standard Library can hand out a fish every day.
Learning every detail of C++ is useful background knowledge, but not as necessary as the ability to fish.


Time, money, and responsibility. The main burden of production code is in maintenance. You want to delegate as much work as possible to somebody else (like the Standard Library). That is the way the business is. With all the std smart pointers and containers the use of raw delete is an unwarranted risk.
closed account (48T7M4Gy)
give Douas a fish and you feed him for a day; teach a man to fish and you feed him for a lifetime


We all have our opinions and perceptions of what the OP wrote. There is absolutely no dispute and never has been as far as I am concerned, that new int [size] is an error - the most basic - something we all have wanted/tried since day one.

But that wasn't my point or question. Douas has packed his bongoes because he has no authority/support for making his comment about new and delete being discouraged - his comment is rash and silly and goes off on a tangent. He is not used to being questioned in good faith and therefore obfuscates and stumps off.

Avoid the same trap - the wheel spiel is about as useful and germane as discussing quantum behavior in a semiconductor.
Douas did not make the "discouraged" comment. He (and I) merely agree with it. Your quarrel should be with LB.


The OP does use global variables with no apparent reason.

The OP input loop overwrites the 'grade' array for each student. Therefore, after the input has completed, only the grades of the last student are in the array.

The OP function 'calcAverage' does use comma-operator on line 54, which is probably a logical error.

The OP does not validate input. Typing text, when a number is expected, will set the input stream into fail-state and all the following input operations from the same stream will fail too.
closed account (48T7M4Gy)
I know that LB made the comment.

All the other extraneous points (platitudes) raised have nothing to do with my first simple question which obviously can't be answered. That's OK and as I expected, but why bother chiming in with more straw men than even Douas threw in before stumping off?

At least your, keskiverto, comments are characteristically helpful to the OP.
Douas did mention Herb Sutter.
Sutter wrote:
Always use the standard smart pointers, and non-owning raw pointers. Never use owning raw pointers and delete, except in rare cases when implementing your own low-level data structure (and even then keep that well encapsulated inside a class boundary).

A member of C++ standard committee writes "never".


Sutter did discourage the use of using namespace std; directive too, except as desperate temporary stopgap measure when large old codebase had to be recompiled urgently with new version of compiler that did implement namespace std.
http://www.gotw.ca/gotw/053.htm
closed account (48T7M4Gy)
I know what Sutter says. I also know as well as we all do the reservations that Stroustrup has about new and delete - right from his invention of new and delete. There is no question about it.

std:: is another case where we have to differentiate between short educational code and full production robust code. However this has nothing to do with the dynamic arrays and my question.

Sutter can say what he likes - he obviously holds an important position but it is not so important that silly dogma must prevail, and he doesn't advocate it in any case. So many times here people like the OP who adopts a simple array structure is jumped on and we read the same irrelevance that 'vectors do the job much better', how boring is that?

Well, all I can say is write a letter to Sutter and tell him to delete those pages from the standard. I wish you luck because my guess is he will see it as a code-nazi having another go.

BTW: The OP hasn't written a class. :))
I don't understand what's going on in this thread anymore.
I dunno. Apparently Nazis are taking away our pointers, and that's boring, so... drama?
Pages: 12