Revisited: difference between static array and dynamic array in C++? - c++

I'm a beginner for C++ and I saw the post here. However, it is very unclear for me what is the benefit of dynamic array.
One advantage is that one can change the length of a dynamic array, here is the code
int *p = new int[10];
// when run out of the memory, we can resize
int *temp = new int[20];
copy(p, temp); // copy every element from p to temp
delete[] p; // delete the old array
p = temp;
temp = nullptr;
Above is for dynamic allocation, it says the array will be on the heap, and need to manually delete it. However, why not use the static array as follow
int array1[10];
int *p = array1;
// when run out of the memory, we can resize
int array2[20];
copy(array1, array2); // copy every elements from array1 to array2;
p = array2;
In this code, we don't need to delete the array1 since it is on the stack area. Here are my question:
what is the benefit of the dynamic array? It seems for me, resizing is not a big issue. People always say the size of static array are fixed, the size of dynamic array is not fixed. Why the size of dynamic array is not fixed. for example, int p=new int[10], the size of p is fixed.
Thanks a lot.

int array1[10];
int *p = array1;
// when run out of the memory, we can resize
int array2[20];
copy(array1, array2); // copy every elements from array1 to array2;
p = array2;
In whichever function, or inner scope, array1 and array2 get declared these arrays get automatically destroyed when the function or inner scope returns. Full stop.
This is why this is called "automatic scope". The fact that there may be a pointer to one of the arrays is immaterial. The array will be gone and any attempt to dereference that pointer will result in demons flying out of your nose.
So if you had any grand designs to continue using this array, in some form or fashion, after returning from the function where they get declared, too bad. It's not going to happen.
On the other hand, after newing something, as long as you properly track the pointer to the newed object(s) they can be used anywhere else, until they get deleted. This function, another function, anywhere. Even a different execution thread.
Having said all of that, you should not be using new or delete either. You should be using C++ library's containers which will correctly handle all memory allocation, deallocation, and copying, for you. In this case, you are simply reinventing what std::vector already does for you, and it will actually do it, in some ways, far more efficient than you can do easily on your own. You just call resize(), and, presto, your vector is bigger or smaller, as the case may be. And, in all other respects the vector will be indistinguishable from your array. It will be very hard to tell the difference.
So, use C++ library's containers. They are your friends. They want you to do memory allocation correctly, on your behalf. Modern C++ code rarely uses new or delete, any more. It's important to understand how it works, but 99% of the time you don't really need it.

Doing your own dynamic array with new int[20] and delete[] etc, is no doubt good for learning how it all works.
In real C++ programs you would use std::vector. Maybe like this:
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> lines;
std::string line;
while (std::getline(std::cin, line)) {
lines.push_back(line);
}
std::cout << "Read " << lines.size() << " lines of input\n";
}
The reason you would use dynamic allocation is so your program can handle any number of lines of any line length. This program can read four lines or 400,000. The std::vector is dynamic. So is std::string.

I have write a code on static and dynamics array, hope this will help.
#include<iostream>
using namespace std;
int main (){
//creating the static array .. rember the syntax of it.
int array[4]= {1,2,3,4}; // size is fixed and can not be changeable at run time.
cout<<"Static Array."<<endl;
cout<<"Printing using index."<<endl;
for(int x=0;x<4;x++){
cout<<"\t"<<array[x];
}
cout<<endl;
cout<<"Printing using pointer."<<endl;
int*ptr= array;
for(int x=0;x<4;x++){
cout<<"\t"<<*ptr++;
}
//delete [] array ;// error, because we can not free the size from stack
// array[6]= {1,2,3,4,5,6}; //Error: We can not change the size of static array if it already defined.
// we can not change the size of the static aray at run time.
cout<<endl;
cout<<"\n\nDynamic Array."<<endl;
int n=4;
//Creating a dynamic Array, remember the systex of it.
int *array2 = new int [n]; // size is not fixed and changeable at run time.
array2[0]= 1;
array2[1]= 2;
array2[2]= 3;
array2[3]= 4;
cout<<endl;
cout<<"Printing using index."<<endl;
for(int x=0;x<4;x++){
cout<<"\t"<<array2[x];
}
cout<<endl;
cout<<"Printing using pointer."<<endl;
int*ptr2= array2;
for(int x=0;x<4;x++){
cout<<"\t"<<*ptr2++;
}
cout<<endl<<endl<<endl;
delete array2; //Size is remove at runtime
cout<<"Chnaging the size of dynamic array at runtime... :)";
// Changing the size of the array to 10.. at runtime
array2 = new int [10]; // Array size is now change to 10 at runtime
array2[0]= 1;
array2[1]= 2;
array2[2]= 3;
array2[3]= 4;
array2[4]= 5;
array2[5]= 6;
array2[6]= 7;
array2[7]= 8;
cout<<endl;
cout<<"Printing using index."<<endl;
for(int x=0;x<7;x++){
cout<<"\t"<<array2[x];
}
// free the memory/ heap
delete [] array2;
return 0;
}
Output

Related

Shrinking the size of a dynamically allocated array in C++ [duplicate]

I have created an array pointer as a global variable like this:
T *bag;
bag = new T[size];
I have a method where I insert things into the array; however, if it detects that it will overflow the array, I need to resize the array (without vectors). I've been reading about this question all over stack overflow but the answers don't seem to apply to me because I need the data from the old array copied into the new array. Additionally, if I create a new array of a larger size inside the method and then copy the data over to the new array, once the method ends, the array will disappear, but I need it to be a global variable again so all my methods can see it...How should I proceed?
Thank you
Memory, allocated by new, would not disappear after your method ends.
You can return pointer to a new array by usung reference: void f(int *&ptr, size_t &size).
Also, be aware, that you need to clear memory manually arter you use it. For example:
int* newArray = new int[newSize];
... copying from old array ...
int* temp = oldArray;
oldArray = newArray;
delete[] temp;
To resize an array you have to allocate a new array and copy the old elements to the new array, then delete the old array.
T * p_bag;
p_bag = new T[old_size];
//...
T * p_expanded_bag = new T[new_size];
for (unsigned int i = 0; i < old_size; ++i)
{
p_expanded_bag[i] = p_bag[i];
}
delete[] p_bag;
p_bag = p_expanded_bag;
You could use std::copy instead of the for loop.
The thing you need can do the following things
Automatically handle the resizing when requested size is larger than current array size.
When resizing, they can copy the original content to the new space, then drop the old allocation immediately .
There is a non-global-variable way mechanism they can track the array pointer and the current size.
The thing is very similar to std::vector. If it is not allowed to use, you may need manage a dynamic allocated resource like std::vector on your own. You can reference the implementation in that answer link.
If eventually you need to wrap it in a class, make sure to follow the big 3 rules (5 rules in C++11)
You can use realloc from c if you have array of chars/ints/doubles... or some other fundamental data type or classes with only those variables (eg. array of strings won't work).
http://www.cplusplus.com/reference/cstdlib/realloc/
bag = (T*) realloc(bag, new_size * sizeof(T));
Realloc automatically allocate space for your new array (maybe into the same place in memory) and copy all data from given array.
"The content of the memory block is preserved up to the lesser of the new and old sizes, even if the block is moved to a new location."
Example:
#include <stdio.h> /* printf*/
#include <stdlib.h> /* realloc, free */
#include <iostream>
int main()
{
int old_size = 5;
int new_size = 10;
int *array = new int[old_size];
printf("Old array\n");
for (int i=0; i<old_size; i++) {
array[i] = i;
printf("%d ", array[i]);
}
printf("\nArray address: %d\n", array);
array = (int*) realloc(array, new_size * sizeof(int));
printf("New array\n");
for (int i=0; i<new_size; i++)
printf("%d ", array[i]);
printf("\nArray address: %d\n", array);
free(array);
return 0;
}

Destruct array of vectors in C++

I have questions about the destructing process of STL vector as well as array of vectors. The only thing I learned from my teacher is the number of delete is equal to the number of new. I have 3 questions for the array of vector in different contexts. To be convenient, all of the array has 5 vectors. Each vector has 1 element.
1. Array of vectors appears in main.cpp
int main(){
int size = 5;
vector<int> *array_vec = new vector<int>[size];
for(int i=0; i<size; i++){
array_vec[i].push_back{i};
}
delete [] array_vec;
return 0;
}
Question 1: At the end of the main() function, I manually delete the array by delete [] array_vec, but I don't manually free each vectors array_vec[i]. Was the array_vec[i]'s memory released automatically? If yes, when? (before OR after my delete [] array_vec?) The reason why I ask this question is for 2D dynamic array, we must free the inner array before the outer array, so I wonder whether it is the case for the array of vector.
2. Array of vectors appears in a class's method as a temporary variable
Class myClass{
public:
void myMethod(){
int size = 5;
vector<int> *array_vec = new vector<int>[size];
for(int i=0; i<size; i++){
array_vec[i].push_back(i);
}
delete [] array_vec;
}
}
int main(){
myClass myclass;
myclass.myMethod();
/** some other process in the program **/
return 0;
}
Question 2: Was the array_vec[i] released before the myclass.myMethod() returned? OR array_vec[i] will only be released at the end of the entire program?
3. Array of vectors appears in a class as a class property
Class myClass{
public:
vector<int> *array_vec;
public:
~myClass(){
if(array_vec)
delete [] array_vec;
}
void Init(){
int size = 5;
array_vec = new vector<int>[size];
for(int i=0; i<size; i++){
array_vec[i].push_back(i);
}
}
void Use(){
std::cout<<array_vec[0][0]<<std::endl;
}
}
int main(){
myClass myclass;
myclass.Init();
myclass.Use();
/** some other process in the program **/
return 0;
}
Question 3: Is my destructor OK? In my ~myClass() method, I just free the array of vectors array_vec, but I do not know whether those vectors themselves will be free automatically or not? If yes, that will be good. If no, when will they be released? How can I manually free those vectors?
This problem has confused me for a long time. The memory issue is very important for my c++ program, because I need to use array of vectors in a big loop. If the memory is not released correctly, the memory usage will be larger and larger while the program is running. In that case, my program will crash. Really appreciate your help.
All of your examples are fine. std::vector takes care of cleaning up the memory it owns. That's why you use it instead of raw pointers.
In all of the cases you posted, you should use a std::vector<std::vector<int>> instead though. That will free you from having to deal with memory management at all, and help avoid easy mistakes, like the rule of three violation in your third example.

c++ 2d arrays and pointers to pointers- I don't understand this code

I don't understand pointers to pointers or pointers to 2d arrays. I do not understand what the following code does. Can anyone go line by line and explain to me what it is doing? It is really important for me to grasp this concept, but I cannot grasp it.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
//i understand that we declare a 2d array
int tD[2][2];
//but then i'm confused why there is a pointer to a pointer when there isn't a pointer in the first place
int **tD2;
//and i am confused what the star after int does
tD2 = new int*[2];
//i think i get this
for(int i = 0; i < 2; i++)
tD2[i] = new int[2];
for(int i = 0; i < 2; i++)
delete [] tD2[i];
//lost here
delete [] tD2;
return 0;
}
I will leave comments to explain...
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
//i understand that we declare a 2d array
int tD[2][2];
//but then i'm confused why there is a pointer to a pointer when there isn't a pointer in the first place
int **tD2; // A 1D array is an int*; int** makes an array of int*'s, which are themselves arrays (not necessarily all next to each other).
//and i am confused what the star after int does
tD2 = new int*[2]; // allocates memory for two int*'s.
/*
int* a = new int[2];
int** b = new int*[2];
int*** c = new int**[2];
See the pattern? It's one less * than the type.
*/
//i think i get this
for(int i = 0; i < 2; i++)
tD2[i] = new int[2];
for(int i = 0; i < 2; i++)
delete [] tD2[i]; // deallocates each inner array.
//lost here
delete [] tD2; // deallocate the outer array. (i.e., the array that holds the "inner arrays").
return 0;
}
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
//i understand that we declare a 2d array
int tD[2][2];
//but then i'm confused why there is a pointer to a pointer when there isn't a pointer in the first place
int **tD2;
This defines tD2 as a pointer (the first *) to a pointer ( the second *) to an int. This isn't useful for anything yet because it is just a pointer and hasn't been pointed at anything. Until it points at something it is dangerous.
//and i am confused what the star after int does
tD2 = new int*[2];
This dynamically allocates an array of two pointers (the *) to ints and assigns this array to tD2. tD2 now points at something and is safe to use. However the array of pointers is uninitialized and dangerous.
//i think i get this
for(int i = 0; i < 2; i++)
tD2[i] = new int[2];
This loop dynamically allocates an array of two ints for each of the pointers in the array of pointers to ints allocated above to point at. Now all of the pointers are pointing at something.
for(int i = 0; i < 2; i++)
delete [] tD2[i];
Any memory you dynamically allocate should be returned to from which it came when you are done with it so the memory can be reused or eventually your program will run out of memory. delete [] returns an array and makes sure the appropriate destructors are called. This loop releases the arrays of int.
//lost here
delete [] tD2;
Releases the array of pointers to ints for the same reasons as above.
return 0;
}
Note: This is a horrible way to manage a 2D array. Look at all the work you had to do. Think of how easy it is to forget or be unable to return the memory that was allocated. The programmer has to remember the dimensions or pass them around with tD2 to make sure no one steps out of bounds.
Don't do this. Instead use std::vector.
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int main() {
//i understand that we declare a 2d array
int tD[2][2];
vector<vector<int>> tD2(2, // outer vector contains 2 vectors
vector(2)); // inner vector contains 2 ints
return 0;
}
vector looks after the memory for you. It knows how big all of the dimensions are so it's harder to get lost. It has a method, at, that won't let you go out of bounds. It gets bigger if you need it to get bigger. Take that dynamic array! Best of all, it has libraries full of support functions for searching, sorting and manipulating. You have to be a fool not to use vector.
Don't be a fool.
If your instructor forces you to be a fool, call them a fool under your breath and pretend you are a fool until you've safely passed the class.

how to allocate dynamic memory to int a[4][3] array

how to allocate run time memory to an array of size[4][3]?
i.e int a[4][3]
If need is to allocate memory to an array at run time than how to allocate memory to 2D array or 3D array.
Editing the answer based on comments. Allocate separately for each dimension. For a 2D array a 2 level allocation is required.
*a = (int**)malloc(numberOfRows*sizeof(int*));
for(int i=0; i<numberOfRows; i++)
{
(*arr)[i] = (int*)malloc(numberOfColumns*sizeof(int));
}
The simplest way to allocate dynamically an array of type int[4][3] is the following
int ( *a )[3] = new int[4][3];
// some stuff using the array
delete []a;
Another way is to allocate several arrays. For example
int **a = new int * [4];
for ( size_t i = 0; i < 4; i++ ) a[i] = new int[3];
// some stuff using the array
for ( size_t i = 0; i < 4; i++ ) delete []a[i];
delete []a;
What have you tried. new int[4][3] is a perfectly valid
expression, and the results can be assigned to a variable with the
appropriate type:
int (*array2D)[3] = new int[4][3];
Having said that: I can't really think of a case where this
would be appropriate. Practically speaking, anytime you need
a 2 dimensional array, you should define a class which
implements it (using std::vector<int> for the actual memory).
A pure C approach is the following:
int (*size)[4][3];
size = malloc(sizeof *size);
/* Verify size is not NULL */
/* Example of access */
(*size)[1][2] = 89;
/* Do something useful */
/* Deallocate */
free(size);
The benefit is that you consume less memory by not allocating intermediate pointers, you deal with a single block of memory and deallocation is simpler. This is especially important if you start to have more than 2 dimensions.
The drawback is that the access syntax is more complicated, as you need to dereference a pointer before being able to index.
Use calloc, i guess this will do.
int **p;
p=(int**)calloc(4,sizeof(int));
In C you can use pointer to pointer
AS #Lundin mentioned this is not 2D array. It is a lookup table using pointers to fragmented memory areas allocated all over the heap.
You need to allocate how many pointers you need and then allocate each pointer. you can allocate fixed size or varaible size depending on your requirement
//step-1: pointer to row
int **a = malloc(sizeof(int *) * MAX_NUMBER_OF_POINTERS);
//step-2: for each rows
for(i = 0; i < MAX_NUMBER_OF_POINTERS; i++){
//if you want to allocate variable sizes read them here
a[i] = malloc(sizeof(int) * MAX_SIZE_FOR_EACH_POINTER); // where as if you use character pointer always allocate one byte extra for null character
}
Where as if you want to allocate char pointers avoid using sizeof(char) inside for loop. because sizeof(char) == 1 and do not cast malloc result.
see How to declare a 2d array in C++ using new
You could use std::vector<> since it is a templated container (meaning array elements can be whatever type you need). std::vector<> allows for dynamic memory usage (you can change the size of the vector<> whenever you need to..the memory is allocated and free'd automatically).
For example:
#include <iostream>
#include <vector>
using namespace std; // saves you from having to write std:: in front of everthing
int main()
{
vector<int> vA;
vA.resize(4*3); // allocate memory for 12 elements
// Or, if you prefer working with arrays of arrays (vectors of vectors)
vector<vector<int> > vB;
vB.resize(4);
for (int i = 0; i < vB.size(); ++i)
vB[i].resize(3);
// Now you can access the elements the same as you would for an array
cout << "The last element is " << vB[3][2] << endl;
}
You can use malloc() in c or new in c++ for dynamic memory allocation.

How can I return a pointer to an array in C++?

Here is my simple code
arrayfunc() should store some numbers in an array, and return the pointer of this array
to main function where the content of the array would be printed
What is the problem with my code?
It only returns the pointer to the first element of the array
Any help will be appreciated.
Thanks in advance.
#include <iostream>
using namespace std;
//The definition of the function should remain the same
int* arrayfunc()
{
int *array[10];
array[0] =new int;
array[1] =new int;
array[2] =new int;
array[3] =new int;
*array[0]=10;
*array[1]=11;
*array[2]=12;
*array[3]=13;
return *array;
}
int main()
{
for(int i=0;i<4;i++)
cout<<*(arrayfunc()+i)<<endl;
return 0;
}
(1) You should allocate your array with new if you want to return it: int* array = new int[10]; [assuming here you want array of ints and not array of int*'s]
(2) to return the pointer to the first element in the array, use return array and not return *array
(3) your array is array of pointers, and not array of ints.
Your array is allocated on stack, so as soon as the function returns, it's freed. So you want to return a pointer to a dead memory.
But you are not doing that, you are just returning the valid (copy of) value of the 0th array item.
So, what you have to do:
The best idea would be to switch to stl containers. You should be using std::vector or something like that.
If you stick to the idea of manual memory management, you have to allocate the array on heap, return it from the function, and perhaps deallocate it in the caller.
Edit:
basically you want the following:
using namespace std;
vector<int> arrayfunc()
{
vector<int> v;
v.push_back(10);
...
return v;
}
...
vector<int> result = arrayfunc();
cout << result[0] << ...
This would be the right C++ way.
(Nitpicking:) You don't need to care about copying the vector, because of the RVO used by all modern C++ compilers.
Allocating an array on heap should be simple, too:
int* array = new int[4];
array[0] = 10;
...
return array;
...
int* array = arrayfunc();
...
delete[] array;
But I would strongly advise to take the former approach (with vector).
This codes seems wrong to me in several levels.
Never return an internal variable of a function. The variable array is only defined in the function, so it should never be returned outside.
Why do you allocate each int by itself with new? I would allocate the entire array at once. If you know the array length and it's constant, consider having it defined statically.
http://msdn.microsoft.com/en-us/library/s1sb61xd.aspx
Just try return array; instead of return *array;