hi..i wanted to do something like this:
Code:int size; cin>>size; int numList[size];
but i get error....how do i make a int array of specific size?
hi..i wanted to do something like this:
Code:int size; cin>>size; int numList[size];
but i get error....how do i make a int array of specific size?
You need to use dynamic memory allocation.
If you forget to delete the memory, it will be lost (at least until your program exits, usually). If you do this too often your program might crash. So, when you're using new, don't forget to use delete too.Code:#include <iostream> int main() { int size; std::cin >> size; int *numList = new int[size]; /* do something */ delete [] numList; /* very important */ }
dwk
Seek and ye shall find. quaere et invenies.
"Simplicity does not precede complexity, but follows it." -- Alan Perlis
"Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
"The only real mistake is the one from which we learn nothing." -- John Powell
Other boards: DaniWeb, TPS
Unofficial Wiki FAQ: cpwiki.sf.net
My website: http://dwks.theprogrammingsite.com/
Projects: codeform, xuni, atlantis, nort, etc.
thanx for the reply.
now if i want to output all the data of the list i would do this ?
it doesnt work though,.Code:while(numList!=0){ cout<<*numList; numList++' }
Arrays don't end in 0 (that is just how C style strings work so they can save their length). You already know the size so just use a for loop and loop from index 0 to size-1.
BTW, in C++ there is little reason to use a dynamic array for this. Use a vector instead:The for loop to output it is the same.Code:#include <iostream> #include <vector> int main() { int size; std::cin >> size; std::vector<int> numList(size); /* do something */ /* no need to delete, its done automatically */ }
Inclusive, of course.You already know the size so just use a for loop and loop from index 0 to size-1.
The nice thing about vectors is that they resize to hold however much data you want. You don't need to know the size beforehand. You can supply a size, if you wish, but that just causes the vector to allocate at least that much memory.Code:std::vector<int> numList(size);
Here's a vector reference: http://cppreference.com/cppvector/index.html
The method you will probably find most useful for vectors is push_back(), which adds something to the end of the vector. That and size(), which returns the number of elements in the vector. You can access elements of a vector just like an array.
dwk
Seek and ye shall find. quaere et invenies.
"Simplicity does not precede complexity, but follows it." -- Alan Perlis
"Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
"The only real mistake is the one from which we learn nothing." -- John Powell
Other boards: DaniWeb, TPS
Unofficial Wiki FAQ: cpwiki.sf.net
My website: http://dwks.theprogrammingsite.com/
Projects: codeform, xuni, atlantis, nort, etc.