Thread: Defining an Array's Length inside a Function possible?

  1. #1
    Registered User
    Join Date
    Jul 2004
    Posts
    27

    Defining an Array's Length inside a Function possible?

    Basically the topic :/
    Is it possible to set an array in a function?
    I'm trying to get it so I can have an array in a class without a set size, and then when I'm ready to set it's size I can do so with a function.

    I don't really have a script, just messing with the idea for now.. Any help appriciated

  2. #2
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Using dynamic allocation (ie new and delete) yes. Using non dynamic allocation: compiler dependant

  3. #3
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Code:
    void somefunc(int size)
    {
      char *buffer = new char[size]; // allocate enough room for size characters
      // do some stuff with buffer
      delete[] buffer; // free the allocate memory
    }
    Then you just call it:
    Code:
    somefunc(10);
    somefunc(20);
    etc

  4. #4
    Registered User
    Join Date
    Jul 2004
    Posts
    101
    Rather than working with error prone dynamic memory you should consider using the standard vector class. Not only can you set the size dynamically, but the vector grows dynamically as well without any extra work on your part. And vectors are safer. They save you from the hassle of memory management and special exception frameworks.

  5. #5
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    But if you don't need all the functionality of the vector class why use it???? Not all memory code needs to use the STL.

    Use malloc.

    And exceptions can be caused by more than just malloc so you do not get away from exceptions by not using it.

  6. #6
    Registered User
    Join Date
    Jul 2004
    Posts
    101
    >>But if you don't need all the functionality of the vector class why use it????
    A better question in my opinion would be why not use it? It would be much better to solve the problem simply and safely first. Then if there are performance problems you can drop to a lower level.

    >>Use malloc.
    new would be preferable in C++.

    >>so you do not get away from exceptions by not using it
    True, but you do escape awkward situations where an exception is thrown and memory must be released. The destructor of a container class will handle that automatically whereas if you manage your own memory you must jump through a few hoops to clean up properly. The water begins to get murky when you needlessly work at such a low level.

  7. #7
    S Sang-drax's Avatar
    Join Date
    May 2002
    Location
    Göteborg, Sweden
    Posts
    2,072
    Quote Originally Posted by Princeton
    True, but you do escape awkward situations where an exception is thrown and memory must be released. The destructor of a container class will handle that automatically whereas if you manage your own memory you must jump through a few hoops to clean up properly. The water begins to get murky when you needlessly work at such a low level.
    Very true, encapsulation greatly helps exception handling.

    More specifically, it reduces the need for rethrowing exceptions:
    Code:
    void f()
    {
      int* p = new int[...];
      try
      {
    	 doSomething(p);
      }
      catch(...)
      {
    	delete[] p;
    	throw;  //Rethrow exception after cleaning up
      }
      delete[] p;
    }
    This could have been written:
    Code:
    void f()
    {
      vector<int> p(...);
      doSomething(p);
    }
    Last edited by Sang-drax : Tomorrow at 02:21 AM. Reason: Time travelling

  8. #8
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    Granted the vector class provides much more functionality and is pure C++ unlike malloc...which whoever docked me points for saying use malloc....you are a moron...I know there is no malloc in C++.

    However noone said you have to be pure C++ or pure C in any one program. My point is that this thread has been hijacked because the original question was about something very simple and yet we have turned it into something very complex.

  9. #9
    Registered User
    Join Date
    Jul 2004
    Posts
    101
    >>I know there is no malloc in C++.
    malloc is valid C++, there is just little use for it because it does not handle constructors properly and new is a cleaner alternative.

    >>which whoever docked me points for saying use malloc....you are a moron...
    I merely stated that new is preferred. I appologize if that insulted you in any way.

    >>My point is that this thread has been hijacked
    I thought your point was that using standard containers is overkill and manual memory management should be preferred. However, I do not feel that the thread has lost it's topicality because the discussion is pertinent to the original question.
    Last edited by Princeton; 08-03-2004 at 08:43 AM.

  10. #10
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    you are a moron...I know there is no malloc in C++.
    Who's the what now? Of course there's malloc in C++!

    Quzah.
    Hope is the first step on the road to disappointment.

  11. #11
    Registered User
    Join Date
    Aug 2003
    Posts
    470
    Back to the original question...Typically a class with templates is used, but I believe that you should be able to do
    Code:
    template<int N__>
    void f()
    {
            int a[N__];               
    }
    Then, you would call f like f<50>() where 50 is the size of the array.

  12. #12
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    you are a moron...I know there is no malloc in C++.
    Who's the what now? Of course there's malloc in C++!

    Quzah.
    You know what we mean Quzah. New and delete are much better for dynamic memory allocation.



    I dunno why people get so bent out of shape about pure C or pure C++.

  13. #13
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Quote Originally Posted by okinrus
    Back to the original question...Typically a class with templates is used, but I believe that you should be able to do
    Code:
    template<int N__>
    void f()
    {
            int a[N__];               
    }
    Then, you would call f like f<50>() where 50 is the size of the array.
    I tried to test your code quickly and see what I got... tried the following and got unexpected results:
    Code:
    #include <iostream>
    #include <cstdlib>
    using namespace std;
    
    template <int N> void f()
    {
        int array[N];
        for( int x = 0; x < N; ++x )
            array[x] = rand();
        for( int y = 0; y < N; ++y )
            cout << array[y] << endl;
    }
    
    int main()
    {
        f<2>();
        cout << "Hello World" << endl;
        f<4>();
        return 0;
    }
    Output was:
    Code:
    41
    18467
    6334
    26500
    Hello World
    19169
    15724
    11478
    29358
    Maybe it's my implementation (MSVC++ 6.0) but it seem the f<4>() call ends up setting the size for both calls. If I switch the order around so that the f<4>() call comes first and the f<2>() call comes last, I get:
    Code:
    41
    18467
    Hello World
    6334
    26500
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  14. #14
    Registered User
    Join Date
    Aug 2003
    Posts
    470
    That's odd. I have msvc++ 7.1 and the output I get for code such as this is
    a's size = 2
    a's size = 4

    Code:
    template<int N__>
    void f()
    {
        int a[N__];
    
        std::cout << "a's size = " << sizeof a/sizeof(int) << std::endl;
    }
    
    int main()
    {
        f<2>();
        f<4>();
    
        return 0;
    }
    I'm pretty sure that msvc++ 6.0 should be able to handle code like this
    Code:
    template<int N__>
    class Static_array {
    public:
           Static_array() { std::cout << "N__ = " << N__ << std::endl; }
    private:
           int a[N__];
    };
    A technique similar to this is described in C++ analysis and design by Booch, somewhat before the addition of namespaces, I think.

  15. #15
    Registered User
    Join Date
    Jul 2004
    Posts
    27
    I don't even know what a vectore class is :P
    If its a windows thing, I don't do it :P

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. doubt in c parser coding
    By akshara.sinha in forum C Programming
    Replies: 4
    Last Post: 12-23-2007, 01:49 PM
  2. variables when declared inside or outside a function
    By jas_atwal in forum C Programming
    Replies: 6
    Last Post: 12-14-2007, 02:42 PM
  3. Replies: 28
    Last Post: 07-16-2006, 11:35 PM
  4. Problem with Visual C++ Object-Oriented Programming Book.
    By GameGenie in forum C++ Programming
    Replies: 9
    Last Post: 08-29-2005, 11:21 PM
  5. im extreamly new help
    By rigo305 in forum C++ Programming
    Replies: 27
    Last Post: 04-23-2004, 11:22 PM