Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamic Memory Allocation.Is it?

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
I understand the definition of dynamic memory allocation.It means that memory for a value to be stored in is allocated while program is allready running.
But isn't array in this example also dynamiclly alocated,I mean memmory for an array is allocated when you read X and that is when program is allready running?

int x=0;
cin>>x;
int y[x]={1}; //Isn't this dynamicly
allocated?Program is
allready running?
 
The statement of int y[x] ={1}; will fail to pass the complier. The size of array cannot be undefined.
 
The situation I think you mean to describe is when you have a CONSTANT as a variable. That situation can be defined because the value will never change. Also in the situation

int x[] = {1,2,3,4};

the constant value can be determined. What is going on is the preprocessor goes through the code, looks for any preprocessor directives, and allocates memory for what it can. In the case of a variable being used to determine the size of an array, you should see an error stating something along the lines of

non const var used to determine const size (or something like that, i have not seen the error in a while)


In order to declare the array dynamically, you would need to do:

int* array;
int x;

cin>>x;

array = new int[x];



I hope this helped clarify it a bit.

Matt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top