3 Replies - 466 Views - Last Post: 21 July 2010 - 11:12 AM Rate Topic: -----

#1 Crunch  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 139
  • View blog
  • Posts: 1,222
  • Joined: 28-July 09

Dynamic array

Posted 21 July 2010 - 05:45 AM

Is it okay to do something like this inside a function

void foo(int a, int B)/>{

int name[b-a];

name[4]= 6;  // assume 4  < b-a  So you can assign a value
}




I think its not good because the return address in the stack may get overwritten.
Is This A Good Question/Topic? 0
  • +

Replies To: Dynamic array

#2 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3088
  • View blog
  • Posts: 19,136
  • Joined: 14-September 07

Re: Dynamic array

Posted 21 July 2010 - 05:52 AM

Not all compilers support VLAs. You also don't do any checking to ensure a-b isn't negative. It would be better to do:


void func(int a, int b ){
    int length = a-b;
    if (length >= 1){
         int* data = new int[length];
         //do stuff with it
    }
    else{
    }
}


Was This Post Helpful? 2
  • +
  • -

#3 jjl  Icon User is offline

  • Engineer
  • member icon

Reputation: 1046
  • View blog
  • Posts: 4,449
  • Joined: 09-June 09

Re: Dynamic array

Posted 21 July 2010 - 07:44 AM

I would typically avoid VLA's, I dont think C++ compilers support them (atleast the ones that i use).
VLA's does have a clear representation of the stack and heap, which will usually is not good when dealing with large sets of memory. KYA showed a good example of using dynamic memory, but you will need to use malloc if you are writting in C rather than C++. And dont forget to free the memory once your are finished :)
Was This Post Helpful? 0
  • +
  • -

#4 Bench  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 854
  • View blog
  • Posts: 2,338
  • Joined: 20-August 07

Re: Dynamic array

Posted 21 July 2010 - 11:12 AM

a dynamic array in C++ is called a vector
#include <vector>
void foo( int a, int b ){

    vector<int> name(b-a);

    name[4]= 6;  // assume 4  < b-a  So you can assign a value
}


Standard C++ has never supported VLA's; I can't really see that it ever will either, on the basis that we already have dynamic arrays which are far better.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1