Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Static binding and Dynamic binding of Array

I've just read through all the search result about the same topic I'm asking right now in stackoverflow and it's not really answer my curiosity.But here's the thing.

The Question

1.)From what i know , static binding means it's set during compile time and it's there during runtime whereas for dynamic binding means it's set during runtime.

2.)So the book i read introduce about dynamic array , it mentions dynamic array size could be set during runtime.Which is done in this way.

The Code

int size;
cin >> size;
int * pz = new int [size]; // dynamic binding, size set at run time
delete [] pz; // free memory when finished


3.)In this code the book mention dynamic array size could be set during runtime.So out out curiosity i try this.

The Code

int size;
cin >> size;
int array[size];
//After the array declaraction i assign value to it to check whether it works or not.


4.)The code above works too , so i just curious what so special about dynamic array since normal static array could did the same job.

5.)Is it because of dynamic array could free its memory during runtime whereas static can't that's what makes it so special??


Thanks for spending time reading my question , do point out any mistake made by me.

like image 302
caramel1995 Avatar asked Jan 19 '23 05:01

caramel1995


2 Answers

Your static array with dynamic size (called a variable length array, short VLA) only works thanks to a language extension in your compiler. It's a C99 thing, which isn't contained in the C++ standard, meaning it won't be portable.

The other obvious difference is that you can pass the pointer to the dynamic array somewhere else, save it somewhere, return it from a function, or in other words, have it outlive the scope it was created in. You can't do that with static arrays, as they are destroyed at the end of their scope.

like image 79
Xeo Avatar answered Feb 01 '23 14:02

Xeo


int size;
int array[size];

will throw a compile time failures saying size is not a compile time constant or expected constant expression.

You declare arrays like these

int array[5]

or

const int size = 100;
int array[size];

when you know the array size well ahead of time.

Otherwise you use the new and delete [] approach. I would recommended avoiding this construct altogether in favor of std::vector

like image 30
parapura rajkumar Avatar answered Feb 01 '23 15:02

parapura rajkumar