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

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.

Related

Revisited: difference between static array and dynamic array in 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

Problem with my dynamic array - Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)

I have a problem when I'm doing my debugging: Xcode gives:
Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)
I think it's a problem with my dynamic array...
My assignment is to calculate the perimeter of a polygon with points.
So, my program receives points (x and y) to fill an array of Points, then I made another array, distance, which I fill with all the distances, and then I can calculate the perimeter.
I don't know if it's very clear but I'm a beginner in C++.
#include <iostream>
#include "Point.h"
#include "Polygone.h"
using namespace std;
int main() {
int numberSide;
int x,y;
Point* array = nullptr;
Polygone myPolygone;
cout<<"enter number of sides:"<<endl;
cin>>numberSide;
float* distance=new float[numberSide];
cout<<"enter points:"<<endl;
for (int i=0; i<numberSide; i++) {
cin>>x>>y;
Point p(x,y);
array[i]=p;
}
for (int i=0; i<numberSide-1; i++) {
distance[i]=array[i].distance(array[i+1]);
}
distance[numberSide]=array[0].distance(array[numberSide]);
myPolygone.perimeter(distance);
delete [] distance;
return 0;
}
You never actually allocate any space for the array variable - you are only declaring it and assigning it a nullptr value. Thus, when you later try executing the array[i]=p; you are trying to dereference a null pointer, which causes your EXC_BAD_ACCESS error.
To fix this, you need to allocate the array, once you know what size it is (i.e. how many sides your polygon has). You should do this in the same way as you allocate the distance array:
cin>>numberSide;
float* distance=new float[numberSide];
Point* array = new Point[numberSide]; // And you should delete the earlier "Point* array = nullptr;` line
Of course, you also need to free the memory when you have finished with it:
delete [] distance;
delete [] array;
return 0;
However, as you are using C++, a far better way than using raw pointers and the new operator is to use the Standard Template Library's std::vector container, which takes care of all allocating and freeing operations internally. Here are the relevant 'replacement' lines:
#include <vector> // This header defines the `std::vector` container
//...
cin>>numberSide;
std::vector<float> distance(numberSide);
std::vector<Point> array(numberSide);
Then you don't need the delete[] lines, as the vectors' memory will be released automatically when the vectors go 'out of scope'. Also, you don't need to really change any of your other code, as the std::vector class has a [] operator, which works as you would want it to.

Calling array with variable size as parameter

I was trying to make a program in which the user decides the dimensions of a 2-D array.
I'm getting an error on the function definition while compiling. Why is this wrong and what would be the correct way to do it?
I'm using the Dev-C++ 5.7.1 compiler (if that's relevant).
#include<iostream>
using namespace std;
int R=0,C=0;
void func(int);
int main() {
cin>>R>>C;
int array[C][R];
// DO STUFF HERE
func(array);
// DO SOME MORE STUFF
return 0;
}
void func(int arr[][R]) {
// DO STUFF HERE
}
ISO-C++ forbids VLAs. To dynamically allocate an array you'll either need to do some raw pointer tricks or use a vector of vectors.
vector of vectors approach:
std::cin >> R >> C;
std::vector<std::vector<int>> array(R, std::vector<int>(C));
The signature for func then becomes (const correctness may be different)
void func(const std::vector<std::vector<int>>& v);
The above is the easier, more maintainable, safer, shorter solution.
With pointers and pointers to pointers you can do it but it becomes more complicated, and you need to delete everything that you new
int R, C;
std::cin >> R >> C;
int **array = new int*[R]; // allocates space for R row pointers
for (int i = 0; i < R; ++i) {
array[i] = new int[C]; // for each row, allocate C columns
}
func(R, C, array);
//then delete everything
for (int i = 0; i < R; ++i) {
delete [] array[i]; // delete all of the ints themselves
}
delete [] array; // delete the row pointers.
with the signature for func being
void func(int r, int c, int **arr);
again, vector of vectors will be a lot easier on you.
An array can be located in two different memory regions - on the stack, or on the heap.
Array like you specified, is located on the stack.
int array[SIZE];
when an array is located on the stack, the compiler needs to know in advance what is its size, therefor SIZE must be a constant expression (known at compile time), and sometimes a defined value (set using #define SIZE 10).
if you want to create an array of unknown size (will be determined in runtime), you need to create the array on the heap, like this:
int **array = new int*[C];
for(int i = 0;i<C; i++)
array[i] = new int[R];
later on, you must remember to delete everything you dynamically allocated (everything you used new on)
for(int i = 0;i<C; i++)
delete[] array[i];
delete[] array;
note the use of delete[], because we are deleting an array (array is an array of arrays of ints, array[i] is an array of ints)
I would recommend passing in a pointer to the array, and two variables for R and C. Then it's up to you to make sure you use pointer math correctly to stay within the bounds of the array.
Otherwise set this up as a template, but you'll still probably need to know the sizes of R & C.

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;