I wrote two functions - one to create two-dimentional double array, and another one to delete it.
double** createMatrix(int n)
{
double **a = new double *[n];
for (int i=0; i < n; i++)
a[i] = new double[n];
return a;
}
void deleteMatrix(double** a, int n)
{
for (int i=0; i < n; i++)
delete [] a[i]; // ERROR HERE
delete []a;
}
Allocated array is working fine. But when I try to free it, I get an error (on a marked line): "project2.exe has triggered a breakpoint.".
I'm using Visual Studio 2012.
edit:
I created a full program:
int main()
{
const int n = 10;
double **m = createMatrix(n);
deleteMatrix(m, n);
return 0;
}
And it's working fine. Also, I found my problem. It was a typo in copyMatrix function.
for (int j=0; j <= n; j++) // should be < instead of <=
a[i][j] = originalMatrix[i][j];
Thanks a lot for your help!
The obvious solution is not to use an array in the first place.
How to create an n x n matrix ?
#include <iostream>
#include <vector>
using Row = std::vector<int>;
using Matrix = std::vector<Row>;
int main() {
size_t const n = 5;
Matrix matrix(Row(n), n);
}
Simple right ? And as a bonus, copy, move and destruction are provided free of charge.
Related
This question already has answers here:
Closed 10 years ago.
The following code is printing garbage values. I am passing an array to a function which adds 5 to every element, but when it returns that array's pointer, the main is showing garbage.
I have tried both indexing and pointers there in main but still same results. How can I fix this?
# include <conio.h>
# include <iostream>
using namespace std;
int * add5ToEveryElement(int arr[], int size)
{
int theArray[5];
for(int i=0; i<size; i++)
{
theArray[i] = arr[i] + 5;
cout<<theArray[i]<<endl;
}
return theArray;
}
void main()
{
const int size = 5;
int noArr[size];
for(int i=0; i<size; i++)
{
noArr[i] = i;
}
int *arr = add5ToEveryElement(noArr, size);
cout<<endl;cout<<endl;
for(int i=0; i<size; i++)
{
cout<<arr[i]<<endl;
}
cout<<endl;cout<<endl;cout<<endl;cout<<endl;
for(int i=0; i<size; i++)
{
cout<<*arr<<endl;
*arr++;
}
getch();
}
theArray is a local array in the function add5ToEveryElement() which you are returning to main(). This is undefined behaviour.
Minimally you can change this line:
int theArray[5];
to:
int *theArray = new int[5];
It'll work fine. Don't forget to delete it later in main(). SInce you modify the original pointer, save it:
int *arr = add5ToEveryElement(noArr, size);
int *org = arr;
// Rest of the code
//Finally
delete[] org;
Returning an array from a function is generally considered bad.
Unless you MUST have a "new" array, I would suggest the typical case in C and C++ is to modify the input array. If the CALLING function wants to have two separate arrays, then it can do so by making it's own copy. Alternatively, you could write your code to have two arrays passed into your function, e.g.
void add5ToEveryElement(int arr[], int arr2[], int size)
{
for(int i=0; i<size; i++)
{
arr2[i] = arr[i] + 5;
cout<<theArray[i]<<endl;
}
}
then your main would call with two array arguments, and if you wish to use the same as input and output it will do that too.
Sure, this isn't exactly the answer to your question, but it gives a "better" solution to your problem.
I generally dislike allocation in functions - especially "hidden" allocation (this function says it's adding 5 to every element, not "allocate array with added 5 to each element". Code should never do surprising things, and allocating memory is a little bit of a surprise if you only asked for adding 5 to each element)
this is the perfect code
# include <conio.h>
# include <iostream>
using namespace std;
int * add5ToEveryElement(int arr[], int size)
{
int *theArray = new int[5];
for(int i=0; i<size; i++)
{
theArray[i] = arr[i] + 5;
cout<<theArray[i]<<endl;
}
return theArray;
}
void main()
{
const int size = 5;
int noArr[size];
for(int i=0; i<size; i++)
{
noArr[i] = i;
}
int *arr = add5ToEveryElement(noArr, size);
int *p = arr;
cout<<endl;cout<<endl;
for(int i=0; i<size; i++)
{
cout<<arr[i]<<endl;
}
cout<<endl;cout<<endl;cout<<endl;cout<<endl;
for(int i=0; i<size; i++)
{
cout<<*arr<<endl;
*arr++;
}
getch();
delete[] p;
}
This is my first time here. I really hope anyone can help me out there. So this is my problem. I keep getting run time error #2 something about a corrupt "arr". But the program runs fine until the end. I can't figure it out.
This is my code:
#include <iostream>
using namespace std;
void main(){
int arr1[3];
int temp;
//INPUT NUMBERS
for (int i=0; i<5;i++)
{
cin>>arr1[i];
}
cout<<endl;
//SORT
for(int c=0;c<5;c++)
{
for (int k=0;k<5;k++)
{
if(arr1[c]<arr1[k])
{
temp=arr1[k];
arr1[k]=arr1[c];
arr1[c]=temp;
}
}
}
for (int m=0; m<5; m++)
{
cout<<arr1[m]<<endl;
}
}
Try this out:
#include <iostream>
using namespace std;
int main()
{
int arr1[5];
int temp;
//INPUT NUMBERS
for (int i = 0; i < 5; i++) {
cin >> arr1[i];
}
cout << endl;
//SORT
for (int c = 0; c < 5; c++) {
for (int k = 0; k < 5; k++) {
if (arr1[c] < arr1[k]) {
temp = arr1[k];
arr1[k] = arr1[c];
arr1[c] = temp;
}
}
}
for (int m = 0; m < 5; m++) {
cout << arr1[m] << endl;
}
}
It compiles properly without any errors. The mistake you had made is in declaring the size of the array. If you want to store 5 in puts, you need to declare an array of size 5. Your code might work, but a good compiler will always give out an error.
The reason being that when you declare an array, you actually create a pointer to the first element of the array. And then, some memory regions are kept for this array, depending on the size. If you try to access an element that is outside these memory regions, you may encounter a garbage value.
Here's your code in ideone.
In main function of my program I've created dynamic array with number of elements specified in variable(after calculations array is deleted):
cin >> bok;
double **macierz;
macierz = new double *[bok];
for(int i = 0; i < bok; ++i){
macierz[i] = new double[bok];
}
Array macierz (matrix in Polish) is used to calculate it's determinant with another function I've written:
#include <iostream>
#include <conio.h>
#include <string>
#include <math.h>
double determinant(double b[][bok],int m);
// there is int main(){ ... }
double determinant(double b[][bok],int m){
int i, j;
double sum = 0,
double **c; //Second array that throws "type 'double' unexpected"
c = new double *[m];
for(int i = 0; i < m; ++i){
c[i] = new double[m];
}
if(m==2){
sum = b[0][0]*b[1][1] - b[0][1]*b[1][0];
return sum;
}
for(int p=0; p<m; p++){
int h = 0,k = 0;
for(i=1; i<m; i++){
for(j=0;j<m;j++){
if(j==p)
continue;
c[h][k] = b[i][j];
k++;
if(k == m-1){
h++;
k = 0;
}
}
}
sum = sum + b[0][p]*(pow((float)-1,p))*determinant(c,m-1);
}
for(int i = 0; i < m; ++i){ //Removing second array
delete[] c[i];
}
delete[] c;
return sum;
}
Here is the place in main function, where above one is used to calculate determinant:
double det;
det = determinant(macierz, bok); //bok was entered by user
The problem is, that array macierz was created as dynamic, to allow user input number, which will be amount of array rows/columns (it's square matrix, so number of rows is equal to number of columns). It worked flawlessly until I've created function which needs this dynamic array as one of arguments.
How the declaration of determinant function should be modified to be able to use macierz array as it's first argument? And one more little thing - also array c in determinant function is throwing errors(it's next dynamic array, but I cannot understand, why it doesn't work - I've created and removed it like the macierz yet compiler is throwing "type 'double' unexpected")
Have a look at shengy's answer on this question for the various ways to pass a 2D array to a function.
I am new to c++ and i was trying to do folloing two things without help of std::vector( This was done earlier)
Define an array of integer and the size of array is not known to me.
Pass this array into another function and output all the values stored in array.
int _tmain()
{
int* a = NULL;
int n;
std::cin >> n;
a = new int[n];
for (int i=0; i<n; i++) {
a[i] = 0;
}
testFunction(a,n);
delete [] a;
a = NULL;
}
void testFunction( int x[], int n)
{
for(int i =0;i<n;++n)
{
std::cout<<x[i];
}
}
But i can see that its not allocating memory of 10 bytes and all the time a single memory is filled up with 0.
Can anyone please help me if i am lacking something ? Or is there any alternative way for this apart from vector.
Thanks in Advance
I modified with one thing as i realized that i put ++n instead of i
int _tmain()
{
int* a = NULL;
int n;
std::cin >> n;
a = new int[n];
for (int i=0; i<n; i++) {
a[i] = i;
}
testFunction(a,n);
delete [] a;
a = NULL;
}
void testFunction( int x[], int n)
{
for(int i =0;i<n;++i)
{
std::cout<<x[i];
}
}
I’m not sure I understand all yours problems but the typo
for(int i =0;i<n;++n) in testFunction led to a very long loop.
Write:
for(int i =0;i<n;++i)
this print yours n "0"
I am solving a quantum-mech problem which requires me to find some eigenvalues by manipulating some matrices. The specifics of this problem is not relevant, I just need help with the c++ problem, I am new to this language and after a couple of hours I figured any more attempts at solving it myself would be futile and so I turn to you for help.
I have this problem where glibc detects an error at the end of my program and I cannot deallocate properly, it is far too big to copypaste here so I will just replicate the part that actually gives the error.
void hamiltonian(int, double **&);
int i,j;
int main()
{
int N = 1000; double **A;
hamiltonian(N, A);
//Physics here
.
.
.
.
.
//Delete
for(i=0; i<N; i++){delete []A[i];}
delete []A;
return 0;
}
void hamiltonian(int N, double **&A)
{
A = new double *[N];
for(i=0; i<N; i++)
{
A[i] = new double[N];
for(j=0; j<N; j++)
{
if(i==j)A[i][j] = 2;
if(i==j+1 || i==j-1){A[i][j] = 1;}
}
}
}
According to my professor I have to deallocate in the same function as I allocate but I didn't even think about deallocation after being nearly done with my project and so I have to rewrite a lot of code, the problem is that I cannot deallocate A inside the hamiltonian function as I need it in other functions (inside //Physics).
Surely there must be a way around this? Might sound a bit ignorant of me but this sounds like a less efficient design if I have to deallocate in the same function as I allocate.
According to my professor I have to deallocate in the same function as I allocate
That is pure silliness. Sometimes (almost always) you need to use the allocated struct outside the function. Definitely false for objects, since constructors and destructors are different functions.
Any way, you can get away without using classes, if you make a Matrix struct and associated newMatrix and deleteMatrix functions :)
#include <cstddef>
#include <iostream>
using namespace std;
struct Matrix
{
int n;
int m;
double** v;
};
Matrix newMatrix (int n, int m)
{
Matrix A;
A.n = n;
A.m = m;
A.v = new double*[n];
for( int i = 0; i < n; i++ ){
A.v[i] = new double[m];
}
return A;
}
Matrix newHamiltonianMatrix (int n, int m)
{
Matrix A = newMatrix(n, m);
for( int i = 0; i < A.n; i++ ){
for( int j = 0; j < A.m; j++ ){
A.v[i][j] = 0.0;
if( i == j ){
A.v[i][j] = 2.0;
}
if( i == j + 1 or i == j - 1 ){
A.v[i][j] = 1.0;
}
}
}
return A;
}
void deleteMatrix (Matrix A)
{
for( int i = 0; i < A.n; i++ ){
delete [] A.v[i];
}
delete [] A.v;
A.v = NULL;
}
int main ()
{
Matrix A = newHamiltonianMatrix(10, 20);
for( int i = 0; i < A.n; i++ ){
for( int j = 0; j < A.m; j++ ){
cout << A.v[i][j] << " ";
}
cout << endl;
}
deleteMatrix(A);
}
delete A;
Needs to be
delete[] A;
If you new[] it, you MUST delete[] it. Also, use a vector- they take care of themselves.
vector<vector<double>> matrix;
There are couple of problems with your code.
(1) You are not allocating memory to the pointer members of A. i.e. A[i] are not allocated with new[]. So accessing them is an undefined behavior.
(2) You must do delete[] for a pointer if it was allocated with new[]. In your other function delete A; is wrong. Use delete[] A;
(3) Using new/new[] is not the only way of allocation. In fact you should use such dynamic allocation when there is no choice left. From your code it seems that you are hard coding N=1000. So it's better to use an 2D array.
const int N = 1000; // globally visible
int main ()
{
double A[N][N];
...
}
void hamiltonian (double (&A)[N][N])
{
...
}