Dynamic array as function argument - c++

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.

Related

Error:No matching function for call to

I am very very new to C++ and I am trying to call the function "jacobi" which performs a user specified number of iterations for the jacobi method (or at least I hope so). On the line where I call 'jacobi' I get the error "No matching function to call to "jacobi". I have read other posts similar to this one and have tried to apply it to my own code but I have been unsuccessful. Maybe there are other issues in my code causing this problem. As mentioned I am very new C++ so any help would be appreciated and please break it down for me.
#include <iostream>
using namespace std;
void jacobi (int size, int max, int B[size], int A[size][size], int init[size], int x[size]){
////
//// JACOBI
////
int i,j,k,sum[size];
k = 1;
while (k <= max) // Only continue to max number of iterations
{
for (i = 0; i < size; i++)
{
sum[i] = B[i];
for (j = 0; j < size; j++)
{
if (i != j)
{
sum[i] = sum[i] - A[i][j] * init[j]; // summation
}
}
}
for (i = 0; i < size; i++) ////HERE LIES THE DIFFERENCE BETWEEN Guass-Seidel and Jacobi
{
x[i] = sum[i]/A[i][i]; // divide summation by a[i][i]
init[i] = x[i]; //use new_x(k+1) as init_x(k) for next iteration
}
k++;
}
cout << "Jacobi Approximation to "<<k-1<<" iterations is: \n";
for(i=0;i<size;i++)
{
cout <<x[i]<< "\n"; // print found approximation.
}
cout << "\n";
return;
}
int main (){
// User INPUT
// n: number of equations and unknowns
int n;
cout << "Enter the number of equations: \n";
cin >> n;
// Nmax: max number of iterations
int Nmax;
cout << "Enter max number of interations: \n";
cin >> Nmax;
// int tol;
// cout << "Enter the tolerance level: " ;
// cin >> tol;
// b[n] and a[n][n]: array of coefficients of 'A' and array of int 'b'
int b[n];
int i,j;
cout << "Enter 'b' of Ax = b, separated by a space: \n";
for (i = 0; i < n; i++)
{
cin >> b[i];
}
// user enters coefficients and builds matrix
int a[n][n];
int init_x[n],new_x[n];
cout << "Enter matrix coefficients or 'A' of Ax = b, by row and separate by a space: \n";
for (i = 0; i < n; i++)
{
init_x[i] = 0;
new_x[i] = 0;
for (j = 0; j < n; j++)
{
cin >> a[i][j];
}
}
jacobi (n, Nmax, b, a, init_x, new_x);
}
The problem:
There are several problems, related to the use of arrays:
You can't pass arrays as parameter by value.
You can't pass multidimensional arrays as parameter if the dimensions are variable
You can't define arrays of variable length in C++
Of course there are ways to do all these kind of things, but it uses different principles (dynamic allocation, use of pointers) and requires additional work (especially for the access of multidimensional array elements).
Fortunately, there is a much easier solution also !
The solution:
For this kind of code you should go for vector : these manage variable length and can be passed by value.
For the jacobi() function, all you have to do is to change its definition:
void jacobi(int size, int max, vector<int> B, vector<vector<int>> A, vector<int> init, vector<int> x) {
int i, j, k;
vector<int> sum(size); // vector of 'size' empty elements
// The rest of the function will work unchanged
...
}
Attention however: the vectors can be of variable size and this jacobio implementation assumes that all the vectors are of the expected size. In professional level code you should check that it's the case.
For the implementation of main(), the code is almost unchanged. All you have to do is to replace array definitions by vector definitions:
...
vector<int> b(n); // creates a vector that is initialized with n elements.
...
vector<vector<int>> a(n,vector<int>(n)); // same idea for 2 dimensional vector (i.e. a vector of vectors)
vector<int> init_x(n), new_x(n); // same principle as for b
...

Modifying a dynamic 2D array in a function

I've got a function that accepts a dynamic multidimensional array (which is initialized to 0) as a parameter, and I'm trying to modify certain values within the array in my function.
The function that accepts the array as a parameter is supposed to simulate the roll of two dice and output the frequency distribution to the array I made that's initialized to zero.
The code for it is as follows:
#include <iostream>
#include <cstdlib>
using namespace std;
int** rollDie(int numRolls, unsigned short seed, int** &rollarray)
{
srand(seed);
int side1, side2;
while (numRolls > 0)
{
side1 = 1 + rand() % 6;
side2 = 1 + rand() % 6;
rollarray[side1][side2]++;
numRolls--;
}
return rollarray;
}
int** initializeArray(void)
{
int i, j;
int** m = new int*[6];
for (i = 0; i < 6; i++)
m[i] = new int[6];
for (i = 0; i < 6; i++)
for (j = 0; j < 6; j++)
m[i][j] = 0;
return m;
}
int main()
{
int numRolls;
unsigned short seed;
int ** a = initializeArray();
cout << "rolls?\n";
cin >> numRolls;
cout << "seed?\n";
cin >> seed;
int ** b = rollDie(numRolls, seed, a);
int i,j;
for (i = 0; i < 6; i++) {
for (j = 0; j < 6; j++) {
cout << b[i][j];
}
cout << "\n";
}
}
Code works for me with just a few issues (I had to guess how you defined a. Next time add that too):
In the printing you should print a space after every number (minor)
In the random, you choose index as 1+rand()%6, so from 1 to 6, but when you print you take indexes from 0 to 5! So your first row and first column will be 0.
Other than that it seems to work.
Only when one goes and does something else does the answer come to mind. I suspect you declared a as:
int a[6][6];
which is an array of 36 integers. In your function, though, you're declaring rollarray to be a pointer to an array of pointers to integers. All you need to do is change the function signature to:
int* rollDie(int numRolls, unsigned short seed, int* rollarray)
As cluracan said, you also want to use array indices in the range 0 to 5.
This is a good case for either the judicious use of print statements or stepping through with a debugger to see what's really going on.

how to delete two-dimentional double array

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.

vector subscript out of range error in c++

I am trying to write a program that takes an input of of n integers, and finds out the one that occurs the maximum number of times in the given input. I am trying to run the program for t cases.
For this, I have implemented a counting sort like algorithm (perhaps a bit naiive), that counts the number of occurrences of each number in the input. In case there are multiple numbers with the same maximum occurrence, I need to return the smaller among those. For this, I implemented sorting.
The issue I am facing is, that every time I run the program on Visual C++, I am getting an error that tells "vector subscript out of range". Under Netbeans, it is generating a return value of 1 and exiting. Please help me find the problem
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int findmax(vector<int> a, int n)
{
int i,ret;
ret = 0;
for ( i = 0; i <n; i++)
{
if (a[i] > ret) {
ret = a[i];
}
}
return ret;
}
int main() {
int i = 0, j = 0, k = 0, n,m,r1,r2;
vector<int> a;
int t;
vector<int> buff;
cin>>t;
while(t--) {
cin>>n;
a.clear();
buff.clear();
for ( i = 0; i < n; i++) {
cin>>a[i];
}
sort(a.begin(),a.end());
m = findmax(a,n);
for ( j = 0; j < m+1; j++) {
buff[a[j]] = buff[a[j]] + 1;
}
k = findmax(buff,m+1);
for ( i = 0; i < m+1; i++) {
if (buff[i] == k) {
r1 = i;
r2 = buff[i];
break;
}
}
cout<<r1<<" "<<r2<<endl;
}
return 0;
}
After a.clear() the vector doesn't have any members, and its size is 0.
Add a call to a.resize(n) to make it the proper size. You also need to resize buff to whatever size it needs to be.
this line it's the culprit:
cin>>a[i];
you must use push_back:
cin >> temp;
a.push_back(temp);
or resize(n) before:
cin>>n;
a.resize(n);
for ( i = 0; i < n; i++) {
cin>>a[i];
}
then you should pass you vector by reference to findmax
int findmax(vector<int> &a, int n)
...
This isn't how you populate an array.
cin>>a[i];
You need to use the push_back() method or pre-allocate the appropriate size.
The problem is that you're illegally using indexes of your vector that don't exist (you never add any items to the vector). Since you know the size, you can resize it after you clear it:
a.clear();
a.resize(n);
buff.clear();
buff.resize(n);
for ( i = 0; i < n; i++) {
cin>>a[i];
}
will be out of range. The vector, as you construct it, has zero size.

Pass an array through a function

I'm trying to pass a simple array through a function to compute the mean.
int main()
{
int n = 0; // the number of grades in the array
double *a; // the array of grades
cout << "Enter number of scores: ";
cin >> n;
a = new double[n]; // the array of grades set
// to the size of the user input
cout << "Enter scores separated by blanks: ";
for(int i=0; i<n; i++)
{
cin >> a[i];
}
computeMean(a, n);
}
double computeMean (double values[ ], int n)
{
double sum;
double mean = 0;
mean += (*values/n);
return mean;
}
Right now the code is only taking the mean of the last number that was inputted.
There's no loop in your function. It should be something like:
double sum = 0;
for (int i = 0; i != n; ++i)
sum += values[i];
return sum / n;
I'm surprised your current version only takes the last number, it should only take the first number, since *values is the same as values[0].
A better solution uses idiomatic C++:
return std::accumulate(values, values + n, 0.0) / n;
std::accumulate should do the trick.
#include <numeric>
double computeMean (double values[ ], int n) {
return std::accumulate( values, values + n, 0. ) / n;
}
Is this a homework question?
You nead to step through all of the values in your array. You're currently outputting the first number in the array divided by the number of items.