Thread: Operator new[] vs. Array

  1. #1
    Registered User
    Join Date
    Dec 2008
    Posts
    65

    Question Operator new[] vs. Array

    Can someone clearly explain why you would do this:
    Code:
    const unsigned int MAX_SIZE = 120;
    
    MyClass *myInstance = new MyClass[MAX_SIZE];
    istead of just this:
    Code:
    MyClass myInstance[MAX_SIZE];
    Also how would you do this if MAX_SIZE is unknown at compile time?

    I have looked around, but nothing explains these concepts clearly, either that or my head is thicker than I thought it was...

    Thanks in advance,

    Cheers!

  2. #2
    Registered User
    Join Date
    Dec 2008
    Posts
    65
    EDIT:
    Let me rephrase; I know that a better method would be to use:
    Code:
    vector<MyClass> myInstance;
    But I also really don't want to go back through all lines of code and change all of that.

    I am working on a program that reads data into this array and the data file will not always be the same size. I want the program to be able to adjust accordingly, without having to recompile. So, is there a way to dynamically allocate an array of MyClass, without knowing the size of the array? Every method I have tried, has called bad_alloc to be thrown.

  3. #3
    The larch
    Join Date
    May 2006
    Posts
    3,573
    So, is there a way to dynamically allocate an array of MyClass, without knowing the size of the array?
    Without knowing how much you are allocating?

    You might need to do it the same way vector does it.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  4. #4
    a newbie :p
    Join Date
    Aug 2008
    Location
    Zurich, Switzerland, Switzerland
    Posts
    91
    Quote Originally Posted by Phyxashun View Post
    Can someone clearly explain why you would do this:
    Code:
    const unsigned int MAX_SIZE = 120;
    
    MyClass *myInstance = new MyClass[MAX_SIZE];
    istead of just this:
    Code:
    MyClass myInstance[MAX_SIZE];
    I think they are different. The first one is dynamic allocation, the second one is static allocation.
    For dynamic one you can write like this:
    Code:
    MyClass *myInstance = new MyClass[];
    For static allocation, size must be known, different with dynamic allocation.

    Check here:
    http://www.dreamincode.net/forums/showtopic38457.htm

  5. #5
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by auralius View Post
    I think they are different. The first one is dynamic allocation, the second one is static allocation.
    For dynamic one you can write like this:
    Code:
    MyClass *myInstance = new MyClass[];
    For static allocation, size must be known, different with dynamic allocation.

    Check here:
    http://www.dreamincode.net/forums/showtopic38457.htm
    No, you cannot, that is illegal.
    Code:
    MyClass* myInstance = new MyClass[SIZE];
    Even if it's dynamic, it still needs the size. You cannot change the size later, either. You must allocate a new array, copy all data over, and then delete the old one.
    But std::vector handles all this for you.
    If you need a faster alternative, you need to look into platform solutions. I made a much faster vector using Win32 API (keep in mind that it would only be faster if the vector is growing constantly and much; otherwise it would just be a waste of flexibility).
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  6. #6
    a newbie :p
    Join Date
    Aug 2008
    Location
    Zurich, Switzerland, Switzerland
    Posts
    91
    I did try and it can compile...
    Let's make it simple:

    Code:
    char *a = new char [];
    a[100] = '0';
    I think, "technically", it is just ok. But i don't think it is a good way of programming.

  7. #7
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    No, it's not possible. You MUST specify a size. And that size must be large enough to accommodate that 100th element, or you will get undefined behavior.
    If the compiler accepts it, technically it will use 0 as size, and that will give you nothing good, if anything.
    Last edited by Elysia; 01-22-2009 at 02:44 AM.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  8. #8
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by auralius View Post
    I did try and it can compile...
    Let's make it simple:

    Code:
    char *a = new char [];
    a[100] = '0';
    I think, "technically", it is just ok. But i don't think it is a good way of programming.
    g++ says:
    Code:
    foo.cpp: In function `int main()':
    foo.cpp:3: error: expected primary-expression before ']' token
    Line 3 happens to be the line with "new" on it.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  9. #9
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Visual C++ actually accepts it, but this clearly shows that it is non-standard.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  10. #10
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Quote Originally Posted by Phyxashun View Post
    EDIT:
    Let me rephrase; I know that a better method would be to use:
    Code:
    vector<MyClass> myInstance;
    But I also really don't want to go back through all lines of code and change all of that.

    I am working on a program that reads data into this array and the data file will not always be the same size. I want the program to be able to adjust accordingly, without having to recompile. So, is there a way to dynamically allocate an array of MyClass, without knowing the size of the array? Every method I have tried, has called bad_alloc to be thrown.
    No you can't do that. You will have to change at least the declaration and allocation of your array, and preferably how it is used. It is possible to create a type that will behave the way you want it to using the same interface, but the simplest option is to use a vector, and change the way you add elements to follow vector conventions. If you don't care for speed you can also use a map<int,Type>, so that "array[100]=initialValue" syntax works.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  11. #11
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Let me rephrase; I know that a better method would be to use:
    Code:
    vector<MyClass> myInstance;
    But I also really don't want to go back through all lines of code and change all of that.
    That is the best option and you should use that from the start.

    However, how large is the code? Vector has a rather similar interface to arrays, so you might not need to change that much lines of code.

    For example, whenever you have a function that accepts a pointer to array and a size variable you can obtain these from the vector:

    Code:
    void foo(X* x, unsigned size);
    
    vector<X> vec;
    foo(&vec[0], vec.size());
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  12. #12
    Registered User
    Join Date
    Dec 2008
    Posts
    65
    It's only 10300 lines, but it is organized very well. I do believe vector is the best route, so I am going to just go through and change all of the assignments to push backs, etc. I was just almost certain that there had to be a way to dynamically allocate an array without knowing the size, but I am probably wrong.

    Thanks for all of the insights.

    Cheers!

  13. #13
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Phyxashun
    I do believe vector is the best route, so I am going to just go through and change all of the assignments to push backs, etc.
    Depending on your exact requirements, you might create the vector with the given size and then use assignment as needed instead of creating an empty vector and then inserting as needed.

    Quote Originally Posted by Phyxashun
    I was just almost certain that there had to be a way to dynamically allocate an array without knowing the size, but I am probably wrong.
    But there is, as in using dynamic memory allocation, as you mentioned in your own first post. It so happens that this would mean manual memory management unless you use a container.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  14. #14
    Registered User
    Join Date
    Apr 2007
    Posts
    141
    This is what the vector template is for. You can use C idioms if you must however. There is a nice little function called realloc(), which is definitely not a recommended C++ idiom. In fact I don't even think there is a standard equivalent via new and delete.

    Here's a nice algo. trick by the way to make reallocation of an array efficient. Keep two size variables, the memory size and the amount used. When you call realloc, grow your memory size by 50% if it doesn't already fit. The complexity of this algorithm is still linear! You typically only rarely have to resize (call realloc) as you grow your array.

  15. #15
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by SevenThunders
    Here's a nice algo. trick by the way to make reallocation of an array efficient. Keep two size variables, the memory size and the amount used. When you call realloc, grow your memory size by 50% if it doesn't already fit. The complexity of this algorithm is still linear! You typically only rarely have to resize (call realloc) as you grow your array.
    std::vector's push_back does something like that, though with a factor of 2 instead of 1.5. std::vector's reserve() can be used to expand by a factor of 1.5.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 05-29-2009, 07:25 PM
  2. Replies: 6
    Last Post: 11-09-2006, 03:28 AM
  3. [question]Analyzing data in a two-dimensional array
    By burbose in forum C Programming
    Replies: 2
    Last Post: 06-13-2005, 07:31 AM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  5. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM