2 Replies - 417 Views - Last Post: 16 March 2012 - 11:34 PM Rate Topic: -----

#1 Cloudyeyes  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 65
  • Joined: 15-May 10

Allocating an array with a function variable

Posted 16 March 2012 - 08:58 PM

I'm attempting to create an array in a function, with its size passed into the function. I'm getting an error saying "expected constant expression," and "cannot allocate an array of constant size 0."

void foo(int size)
{
	int arr[size];
}

Is This A Good Question/Topic? 0
  • +

Replies To: Allocating an array with a function variable

#2 aaa111  Icon User is offline

  • D.I.C Regular

Reputation: 88
  • View blog
  • Posts: 284
  • Joined: 21-February 07

Re: Allocating an array with a function variable

Posted 16 March 2012 - 10:48 PM

You are trying to allocate array at runtime which is supported by C99 standard only and called Variable Length Array(VLA).If you want to allocate memory with variable size you have to use malloc unless you have C99 specific compiler.Read more about VLA here:
http://drdobbs.com/184401444
Was This Post Helpful? 1
  • +
  • -

#3 Hezekiah  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 208
  • View blog
  • Posts: 552
  • Joined: 12-July 09

Re: Allocating an array with a function variable

Posted 16 March 2012 - 11:34 PM

As aaa111 said, your code will work in C99, but in C++ or C90, you'll have to manually allocate and deallocate the array on the heap:
//C++
void foo(int size) {
    int* arr = new int[size];
    //use arr
    delete[] arr;
}

//C90
void foo(int size) {
    int* arr = malloc(sizeof(int) * size);
    //use arr
    free(arr);
}

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1