Passing 2D array to a function without using vectors [duplicate] - c++

This question already has answers here:
Passing a 2D array to a C++ function
(17 answers)
Closed 1 year ago.
I am writing a program to print the sum of the elements of a user entered square matrix in the form of a 2D array without using vector. However I am getting 2 errors:
Error 1: error:array has incomplete element type 'int []'.
Error 2:
error: expected expression cout<<sumarr(arr[][]
This is my program:
int sumarr(int arr[][]) // ERROR 1
{
// finging no. pf rows(or coloums) of the square matrix
int n = sizeof(arr) / (2 * sizeof(int));
int sum = 0;
for (int i = 0; i < n; i++) // calculating sum of elements
{
for (int j = 0; j < n; j++)
{
sum += arr[i][j];
}
}
}
int main()
{
int n; // No. of rows(or coloumns) of the square matrix
cin >> n;
int arr[n][n];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++) // inputting array elements
{
cin >> arr[i][j];
}
}
cout << sumarr(arr[][]); // ERROR 2
return 0;
}
Can someone suggest why I am getting these errors and how to resolve them?

In the function parameter (Error 1) you'll need to specify at least the last dimension of the array:
int sumarr(int arr[][SIZE]){ /*...*/}
In the call to the function you need to use the array name only, no dereferencing necessary (Error 2):
cout << sumarr(arr);
The problem then becomes the fact that Variable Length Arrays are not allowed in C++, so you probably should rethink the possibility of using vectors for this task.
Another thing worth mentioning is that sizeof(arr) inside the function will not render you the size of the array but the size of the pointer, which is what arr becomes when passed as an argument.
Alternatively you can manually allocate memory for the array, it could look more or less like this:
Live sample
#include <iostream>
#include <cassert>
// since sizeof arr can't work you should pass the size as argument
int sumarr(int **arr, int n)
{
assert(n > 0 && n < 1000); // confirm that n is valid, > 0 and a suitable upper limit
int sum = 0;
for (int i = 0; i < n; i++) //calculating sum of elements
{
for (int j = 0; j < n; j++)
{
// input and sum in the same loop will save you a O(N^2) operation
std::cin >> arr[i][j];
sum += arr[i][j];
}
}
return sum;
}
int main()
{
int n; //No. of rows(or columns) of the square matrix
std::cin >> n;
// memory allocation for 2D array
int **arr = new int *[n];
for (int i = 0; i < n; i++)
{
arr[i] = new int[n];
}
//end
int sum = sumarr(arr, n); // passing array and size
std::cout << "Sum: " << sum;
// freeing memory after use
for (int i = 0; i < n; i++)
{
delete [] arr[i];
}
delete [] arr;
//end
}

Related

Code Exiting on above 500,000 number of input

I was performing sorting algorithm to calculate their runtime to execute, in which I was giving millions of number of input to sort, but my code is exiting on above 500,000 input and not showing any output. Is there anyway I can solve it.
int size;
cout<<"Enter size of the array: "<<endl;
cin>>size;
int a[size];
for(int i=0;i<size;i++)
{
a[i]=rand()%size;
}
int temp = 0;
double cl=clock();
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
if (a[j] < a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
double final=clock()-cl;
cout<<final/(double)CLOCKS_PER_SEC;
}
You code crashes on 500'000 input because of stack overflow, you're allocating array on stack of too big size:
int a[size];
Stack size is usually few megabytes at most.
Also it is probably an extensions not of all compilers to have dynamically allocated array on stack, usually size should be a compile time constant.
To overcome stack crash either you have to use std::vector which can provide any size as big as there is free memory, for that do:
std::vector<int> a(size);
(also #include <vector>). Or you may use dynamically allocated array through new operator:
int * a = new int[size];
For this case don't forget to do delete[] a; at the end of program (see docs here).
Don't forget that input 500'000 takes very much of time using your bubble sort. For example 10 times less, 50'000, takes around 10 seconds on my machine.
Full working code using std::vector plus code formatting:
Try it online!
#include <iostream>
#include <vector>
using namespace std;
int main() {
int size;
cout << "Enter size of the array: " << endl;
cin >> size;
std::vector<int> a(size);
for (int i = 0; i < size; i++) {
a[i] = rand() % size;
}
int temp = 0;
double cl = clock();
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
if (a[j] < a[i]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
double final = clock() - cl;
cout << final / (double)CLOCKS_PER_SEC;
}

Finding max value in a array

I'm doing a program that finds the max value in a array. I done it but I found a strange bug.
#include<iostream>
using namespace std;
int main() {
int n; //input number of elements in
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i]; //input array's elements
} int max_value = arr[0];
for (int i = 1; i <= n; i++) {
if (arr[i] > max_value) {
max_value = arr[i];
}
} cout << max_value;
return 0;
}
When I put 5 as first line for the number of elements and 2, 7, 6, 8, 9 as the elements of the array. It returns 16 instead of 9. Please help
In Arrays the first index starts with 0 and ends in n - 1 assuming the array is of length n
so when looping from i = 1 to i <= n. n is now larger than n - 1.
the solution would be to start from 0 and end at i < n hence:
#include<iostream>
using namespace std;
int main() {
int n; //input number of elements in
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i]; //input array's elements
} int max_value = arr[0];
for (int i = 0; i < n; i++) {
if (arr[i] > max_value) {
max_value = arr[i];
}
}
cout << max_value;
return 0;
}
you could also use the std::max function like so:
for(int i = 0; i < n; i ++) {
max_value = max(max_value, arr[i]);
}
The other posts already pointed out problem in your code.
You should be aware of that int arr[n]; is not permitted in standard C++.
[GCC and CLANG compiler support it in C++ as an extension]
An alternative is to allocate memory dynamically:
int *arr = new int[n];
and to find maximum value you can use std::max_element:
int max_value = *(std::max_element(arr, arr + n));
Instead of dynamic array, its better to use vector STL (make yourself familiar with Containers Library). You can do:
std::vector <int> arr;
for (int i = 0; i < n; i++) {
int input;
std::cin >> input;
arr.push_back(input);
}
int max_value = *std::max_element(arr.begin(), arr.end());
std::cout << "Max element is :" << max_value << std::endl;
in your second for do this
for (int i = 1; i < n; i++) {
if (arr[i] > max_value) {
max_value = arr[i];
}
delete '=' from i <= n because i is index which start from 0
and instead of this
int arr[n];
do this
int *arr = new int[n];

Function that accepts a 2D array, multiplies it by an integer, and returns the new 2D array in C++?

say I have a 3x4 array with integer elements, I want to pass this array to a function that then takes all of the elements and multiplies them by some integer 'b' then returns this new array, how would I go about it? this is what I have currently
#include <iostream>
#include <math.h>
using namespace std;
// my function for multiplying arrays by some integer b
int* multarray(int (*a)[4], int b)
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
*(*(a+i)+j) *= b;
}
}
return *a;
}
int main()
{
// creating an array to test, values go from 1-12
int arr [3][4];
int k = 1;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
arr[i][j] = k;
k++;
}
}
// trying to setup new 'array' as a product of the test array
int *newarray;
newarray = multarray(arr,3);
// printing values (works with *(newarray+i) only)
for (int i = 0; i < 3; i++)
{
for (int j=0; j<4; j++)
{
cout << *(*(newarray+i)+j);
}
}
return 0;
}
this works if I don't include the j part when printing all my values but as it is now, tells me I have an error: invalid type argument of unary '*' (have 'int')
Your function is not returning a new array, it's modifying an existing array. So (assuming this is not a problem for you) you should just change the return type to void.
void multarray(int (*a)[4], int b)
{
...
}
Then
multarray(arr,3);
for (int i = 0; i < 3; i++)
{
for (int j=0; j<4; j++)
{
cout << *(*(arr+i)+j);
}
}
If you really do want a function that returns a new array, then that's a whole different (and much more complicated) problem . Apart from anything else it's, strictly speaking, impossible to return an array in C++.

C++ 2D Array - Error invalid types ‘int[int]’ for array subscript

I am trying to create MxN matrix using 2D-arrays in C++.
The createMatrix() function asks for user input for matrix items and the printMatrix() function has to print the matrix.
But the printing task is not working (I can't access the array created, I don't understand why)
I receive the error :
matrix.cpp:35:20: error: invalid types ‘int[int]’ for array subscript
cout << matrix[i][j];
The code I'm working with is:
#include "iostream"
using namespace std;
// user input matrix
int createMatrix(int m, int n){
int arr[m][n];
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
cout << "A[" << i << "][" << j << "] : ";
cin >> arr[i][j];
}
cout << endl;
}
return arr[m][n];
}
/*
void printMatrix(int matrix[][2], int m, int n){
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
cout << matrix[i][j];
}
}
}
*/
int main(){
int m = 2, n = 2; // m = rows, n = columns
int matrix = createMatrix(m,n);
// printMatrix(matrix, m, n); // not working as sub-routine too, main target to make it work with sub-routine
// to print matrix
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
cout << matrix[i][j];
}
}
return 0;
}
matrix is an int not an int[][]. Since it is an int there is no subscript operator and that is why you are getting the error you are getting. You are also using veriable length arrays which is not standard C++. I would suggest you change your code to use a std::vector like
std::vector<std::vector<int>> createMatrix(int m, int n)
{
std::vector<std::vector<int>> arr(m, std::vector<int>(n));
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
cout << "A[" << i << "][" << j << "] : ";
cin >> arr[i][j];
}
cout << endl;
}
return arr;
}
And then main() would be:
int main(){
int m = 2, n = 2; // m = rows, n = columns
std::vector<std::vector<int>> matrix = createMatrix(m,n);
// printMatrix(matrix, m, n); // not working as sub-routine too, main target to make it work with sub-routine
// to print matrix
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
cout << matrix[i][j];
}
}
return 0;
}
Your matrix is not array. it is int.
You need to work with the pointers.
Yes, createMatrix works but you won't be able to do anything with what it created. Because:
arr[n][m] is local (and out of boundaries by the way). It is not a matrix as you probably thought but an item of arr at position [n][m].
It is not well defined to declare array of fixed sizes with vary sizes that depend on function input.
You need to pass to createMatrix array from the main() as pointer (like you did in printMatrix) and createMatrix should work with it and not something local.
Now regarding your original question:
But the printing task is not working (I can't access the array
created, I don't understand why)
matrix was defined as int, not as array.
int matrix = createMatrix(m,n);

returning a two dimensional array from a function in c++ [duplicate]

This question already has answers here:
Returning multidimensional array from function
(7 answers)
Closed 9 years ago.
I want to use a two dimensional int array which is returned from a function
how should I define the function return value ?
I used int** but the compiler gave error:
int** tableCreator(){
int** table=new int[10][10];
for(int xxx=1;xxx<10;xxx++){
for(int yyy=1;yyy<10;yyy++){
table[xxx][yyy]=xxx*yyy;
}
}
return(table); //Here:cannot convert from 'int (*)[10]' to 'int **'
}
Try this:
#include <cstdio>
#include <cstdlib>
int** createTable(int rows, int columns){
int** table = new int*[rows];
for(int i = 0; i < rows; i++) {
table[i] = new int[columns];
for(int j = 0; j < columns; j++){ table[i][j] = (i+j); }// sample set value;
}
return table;
}
void freeTable(int** table, int rows){
if(table){
for(int i = 0; i < rows; i++){ if(table[i]){ delete[] table[i]; } }
delete[] table;
}
}
void printTable(int** table, int rows, int columns){
for(int i = 0; i < rows; i++){
for(int j = 0; j < columns; j++){
printf("(%d,%d) -> %d\n", i, j, table[i][j]);
}
}
}
int main(int argc, char** argv){
int** table = createTable(10, 10);
printTable(table, 10, 10);
freeTable(table, 10);
return 0;
}
You need the second loop to allocate a 2-d array in C and similar operation to free it. a two-D array is in essence an array of arrays so can be expressed as a pointer array. the loop initializes the arrays pointed to the pointers.
Clarifying as per conversation with #Eric Postpischil below: changed createTable to take row/column count for truly dynamic allocation.
int** table=new int[10][10];
this is wrong. you cannot allocate space for 2D dynamic array in this way in C/C++.
Meanwhile, you declared array size as 10, so indices are from 0-9, but you are trying to assign values to index 10 in your nested for loops, which is not right too.
You may do the following for allocation:
int** table = new int*[10];
for (int i = 0; i < 10; ++i)
{
table[i] = new int[10];
}
Usually, the type used to point to an array is a pointer to an element of the array. Since a two-dimensional array of int is an array of array of int, you want a pointer to array of int. The C++ syntax for this type is int (*)[N], for some dimension N. This code demonstrates:
#define N 10
int (*tableCreator())[N]
{
int (*table)[N] = new int[N][N];
for (int i = 0; i < N; ++i)
for (int j = 0; j < N; ++j)
table[i][j] = i*j;
return table;
}
#include <iostream>
int main()
{
int (*t)[N] = tableCreator();
for (int i = 0; i < N; ++i)
{
for (int j = 0; j < N; ++j)
std::cout << t[i][j] << ' ';
std::cout << '\n';
}
delete [] t;
return 0;
}
I. Arrays are not pointers.
II. Why not vector<vector<int> >?
III. If not, then:
typedef int Int10Array[10];
Int10Array *arr = new Int10Array[10];
IV. Why write past the bounds? Do you want explicit nasal demons?
for(int xxx = 0; xxx < 10; xxx++)
^^^ ^^^^