-
C++ question about arrays....
Hello.
I'm working on a program that is about to get student's information.
so when a student uses the program, a field of memory should be allocated to him/her to save his/her information.
unfortunaly i dont know how many students there are, so i cant use arrays because of constant size..therefor linked lists are being used...
But i was wondering if this idea would work too or not:
Code:
const int OldSIZE=5;
int *p=new int[OldSIZE];
so we have an array with size of 5 that can hold 5 student's records and can be accessed by pointer "p".
here is my idea and my problem that if we have a new student to save his/her data, how can i make a new array with new size that the new size is 1+OldSIZE and copy all information plus new students information to the new array?
Code:
size=size+1;
//size is 6 now. but we cant do it because it is constant
int *q=new int[size];
a code that can copy (array of pointer p) to (array of pointer q);
delete []p;
add the new student's info to the new array..
how can i make this idea work??
i hope i could explain it clearly, but ask me if ur confused what i meant...
-
Re: C++ question about arrays....
-
Re: C++ question about arrays....
allocate new block of size+growth factor, loop through old block copying each element as you go to the new block, delete[] the old block. BTW manual memory management is a cardinal sin for stuff like this when you have tools such as std::vector in your arsenal. std::vector is a dynamic array that takes care of all the memory management for you. What you are doing is simulating a rudimentary std::vector
-
Re: C++ question about arrays....
That's what I was going to say - why not just use a std::vector??
-
Re: C++ question about arrays....
Quote:
Originally Posted by
salar
Hello.
I'm working on a program that is about to get student's information.
so when a student uses the program, a field of memory should be allocated to him/her to save his/her information.
unfortunaly i dont know how many students there are, so i cant use arrays because of constant size..therefor linked lists are being used...
But i was wondering if this idea would work too or not:
Code:
const int OldSIZE=5;
int *p=new int[OldSIZE];
so we have an array with size of 5 that can hold 5 student's records and can be accessed by pointer "p".
Use vector, and make things much easier.
Code:
#include <vector>
#include <iostream>
using namespace std;
int main()
{
int num;
cout << "How many? :";
cin >> num;
vector<int> p(num);
// now p can be used just like an array of int.
//...
}
That entire code allocates an "array" of num integers. Not only that, it destroys the array correctly. Not shown -- you can resize the array, insert elements anywhere within the array, etc., all without you having to do dynamic allocation by hand.
So why are you not using this very simple, standard approach?
Regards,
Paul McKenzie
-
Re: C++ question about arrays....
isnt there any other ways than vectors??
actually any other SIMPLE ways....
-
Re: C++ question about arrays....
Quote:
Originally Posted by
salar
isnt there any other ways than vectors??
actually any other SIMPLE ways....
std::vector IS the simple way.
The other simple alternative is to use an std::list. Or an std::deque.
The alternative is either writing your own container (not simple), but you'd just end up with a vector clone. Or to manually manage memory through the use of new[] and delete[] (not simple either).
-
Re: C++ question about arrays....
As said, you could use a vector, but if a list is an appropriate container, why try to force it into an array?
-
Re: C++ question about arrays....
Quote:
Originally Posted by
GCDEF
As said, you could use a vector, but if a list is an appropriate container, why try to force it into an array?
because i need to use binary search to find students.
binary search is not good for a list as i know is it?
-
Re: C++ question about arrays....
Quote:
Originally Posted by
salar
because i need to use binary search to find students.
binary search is not good for a list as i know is it?
No it's not. If you need to search, a map would be perhaps a better container choice. If you want to use a binary search, your array would have to be sorted.
-
Re: C++ question about arrays....
Quote:
Originally Posted by
salar
isnt there any other ways than vectors??
actually any other SIMPLE ways....
If this is a school project and if you are restricted to NOT use STL, check out realloc
-
Re: C++ question about arrays....
Quote:
Originally Posted by
salar
isnt there any other ways than vectors??
actually any other SIMPLE ways....
OK, I'll ask you -- what is difficult about what I posted?
Regards,
Paul McKenzie
-
Re: C++ question about arrays....
To point out what others have said, if you are not restricted in what you can use for this, then use the STL. The time you spend learning how to use vectors, for example, will be extremely useful later on. You will probably spend more time debugging dynamic memory allocation and management. Let the STL do the work for you if you can.
-
Re: C++ question about arrays....
Quote:
Originally Posted by
Paul McKenzie
OK, I'll ask you -- what is difficult about what I posted?
Regards,
Paul McKenzie
Its not difficult, i meant a way by using normal arrays with pointers and new/delete operators...
as VladimirF noticed it is a school project that my teacher has not thought us of vectors and gave us the project. so i think it should be done in another way...is there?
-
Re: C++ question about arrays....
Quote:
Originally Posted by
VladimirF
If this is a school project and if you are restricted to NOT use STL, check out
realloc
Nop i dont think we are allowed.:D
anyways thanks for the link.
-
Re: C++ question about arrays....
Quote:
Originally Posted by
VladimirF
If this is a school project and if you are restricted to NOT use STL, check out
realloc
I'm not sure you can use realloc in conjunction with 'new[]' and 'delete[]'.
Viggy
-
Re: C++ question about arrays....
Quote:
Originally Posted by
MrViggy
I'm not sure you can use realloc in conjunction with 'new[]' and 'delete[]'.
I am sure I should't.
But I am also sure - I can:
Code:
int _tmain(int argc, _TCHAR* argv[])
{
char* p = new char[16];
strcpy(p, "this is a test");
p = (char*)realloc(p, 10000);
free(p);
return 0;
}
If you look at the current MS, for example, implementation of new(), you'll find malloc().
-
Re: C++ question about arrays....
Quote:
Originally Posted by
salar
Nop i dont think we are allowed.:D
There obviously are MANY ways to do what you want. But only you know the restrictions placed on your project.
So – what SHOULD you use? And what exactly is your question?
-
Re: C++ question about arrays....
Quote:
Originally Posted by
VladimirF
I am sure I should't.
But I am also sure - I can:
Code:
int _tmain(int argc, _TCHAR* argv[])
{
char* p = new char[16];
strcpy(p, "this is a test");
p = (char*)realloc(p, 10000);
free(p);
return 0;
}
If you look at the current MS, for example, implementation of new(), you'll find malloc().
Well, yeah. I didn't think it would be an issue with POD. What about objects that have real constructors and destructors?
Viggy
-
Re: C++ question about arrays....
Quote:
Originally Posted by
VladimirF
I am sure I should't.
But I am also sure - I can:
Code:
int _tmain(int argc, _TCHAR* argv[])
{
char* p = new char[16];
strcpy(p, "this is a test");
p = (char*)realloc(p, 10000);
free(p);
return 0;
}
If you look at the current MS, for example, implementation of new(), you'll find malloc().
I think code like this could be a problem. free wont call destructors and replacing it with delete[] wont work as realloc will not do new[]'s bookkeeping. Could lead to resource leaks if the type being stored releases resources in the destructor. Seems crazy to recommend something like that when its ubersimple to new[] a new block and copy the contents of the old block over to the new block, or even if c++0x is being used, moved over rather than copied.
-
Re: C++ question about arrays....
Quote:
Originally Posted by
MrViggy
Well, yeah. I didn't think it would be an issue with POD. What about objects that have real constructors and destructors?
That will get ugly. The constructor, of course, will be called by new(), but free() will not call destructor.
-
Re: C++ question about arrays....
Quote:
Originally Posted by
Russco
I think code like this could be a problem. free wont call destructors and replacing it with delete[] wont work as realloc will not do new[]'s bookkeeping. Could lead to resource leaks if the type being stored releases resources in the destructor. Seems crazy to recommend something like that when its ubersimple to new[] a new block and copy the contents of the old block over to the new block, or even if c++0x is being used, moved over rather than copied.
I agree, 100%. My argument was purely academical. I do NOT recommend to pair new() with free().
-
Re: C++ question about arrays....
mixing alloc/free with new/delete is undefined behaviour 100% of the time. POD is not enough to guarantee compatibility.
The standard does not give one single situation were it is legal.
The fact that you are mixing them and it doesn't crash is because undefined behaviour doesn't guarantee a crash.
-
Re: C++ question about arrays....
Quote:
Originally Posted by
salar
i meant a way by using normal arrays with pointers and new/delete operators...
If expert programmers mess up using new/delete, I hold little chance that a beginner will get it right.
It is not "easy" to use dynamically allocated memory, unless
1) you know exactly what you're doing at every single step and
2) if there is a problem, you know how to diagnose and fix it.
There was a recent thread here that I was involved in -- it must have been over 50 posts in legnth, trying to get a student in getting a dynamic array working correctly, and I still don't think it was correct.
Quote:
as VladimirF noticed it is a school project that my teacher has not thought us of vectors and gave us the project. so i think it should be done in another way
Why not ask the teacher? The goal of your assignment is to do something with student information -- I see no request in writing a dynamic array class. So you'll spend all of your time (as you're doing now), trying to get a dynamic array to work, and the time is flying by without completing the real goal of the assignment, which is to manage student information.
Yes, code your own dynamic array. The problem is that beginner C++ students, going by my experience, never codes one correctly. Even many C++ teachers don't get it right.
Regards,
Paul McKenzie
-
Re: C++ question about arrays....
I feel a need to defend myself for some reason.
In no way did I advocate mixing new with free. I merely stated that a particular compiler, in its particular version, might implement them the same way. And only then you pay no penalty for such major mistake.
As for the use of dynamic arrays or other dynamic memory allocations – I see a point in teaching those things. If for no other reason than to later point: and now see how much better STL containers are! May be it will be easier to demonstrate the benefits of proper design if you can show potential danger of doing otherwise?
-
Re: C++ question about arrays....
Quote:
Originally Posted by
VladimirF
I feel a need to defend myself for some reason.
In no way did I advocate mixing new with free. I merely stated that a particular compiler, in its particular version, might implement them the same way. And only then you pay no penalty for such major mistake.
As for the use of dynamic arrays or other dynamic memory allocations – I see a point in teaching those things. If for no other reason than to later point: and now see how much better STL containers are! May be it will be easier to demonstrate the benefits of proper design if you can show potential danger of doing otherwise?
Personally I think that STL use should be taught before dynamic allocation. Of course you need to learn both but why start with the more low level concept. Should we all learn asm before C++? No, of course not, however once you know C++ and start to look at how the compiler is translating your high level language to machine code, then and only then is a knowledge of assembly helpful. I view dynamic allocation the same way. I dont think you are ready to learn about that until you have at least become familiar with the higher level concepts. Look at the OP. He is messing with dynamic allocation and asks how to copy objects which surely is prerequisite knowledge. You must fully understand copying to get dynamic allocations right. Maybe learn about RAII before dynamic allocation too instead of the more normal other way around. Another analogy. Dont most people learn to drive before they learn car maintenance? Isn't this the same? How many drivers know exactly how the internal combustion engine works? Is that knowledge needed to drive?
The other benefit of doing things this way around is that most of the time when you would have been tempted into manual dynamic allocations, your first thought will now be to reach for a container class and so limiting the allocations made manually therefore in theory lessening the chances of bugs creeping in. Your code will naturally be easier to debug, well once you have learnt how to make sense of the error messages anyway.:eek:
-
Re: C++ question about arrays....
Quote:
Originally Posted by
Russco
Personally I think that STL use should be taught before dynamic allocation. Of course you need to learn both but why start with the more low level concept.
I respectfully disagree. Programmers who never used dynamic memory (and made mistakes) often do not understand why you need to reserve some space in a vector, for example. Just because you said so? Try to remember that!
Understanding how things work sure helps you in controlling them, even on a higher level.
Funny that you used a car example. I had a very similar argument with my older brother many years ago. My point is that if you know what (approximately) is going on when you step on a break, you’d have easier time understanding different breaking techniques.
Paraphrasing famous quote: understanding few principals relieves you from memorizing a lot of facts.
-
Re: C++ question about arrays....