When we define an array C allocates needed memory to it.
This allocates 10 bytes of memory. When should we use malloc() or new()?Code:char c[10];
When we define an array C allocates needed memory to it.
This allocates 10 bytes of memory. When should we use malloc() or new()?Code:char c[10];
Learn C++ (C++ Books, C Books, FAQ, Forum Search)
Code painter latest version on sourceforge DOWNLOAD NOW!
Download FSB Data Integrity Tester.
Siavosh K C
You use new when you are not sure how much memory you want to allocate while compiling your program. eg: you want the user(or a file from which you might read data) to specify the size of the array...
I don't think any one uses malloc in c++ programs...
There may be times when you don't know at compile time weather memory should be allocated or not, for example
Code:MyClass *CreateObject() { if (NeedMoreObjects()) return new MyClass; return 0; }
You also use it when something is supposed to survive the ending of a function:
Code:void func() { char array[10]; } // With this line, the memory is gone again.
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law
OK Thanks
Learn C++ (C++ Books, C Books, FAQ, Forum Search)
Code painter latest version on sourceforge DOWNLOAD NOW!
Download FSB Data Integrity Tester.
Siavosh K C
also if the data will happen be too large for the stack..
Take a look at my thread, "I use stupid thread titles".
Learn C++ (C++ Books, C Books, FAQ, Forum Search)
Code painter latest version on sourceforge DOWNLOAD NOW!
Download FSB Data Integrity Tester.
Siavosh K C