Passing Multidimenionall Arrays through C++ functiones [duplicate] - c++

This question already has answers here:
Passing a 2D array to a C++ function
(18 answers)
Closed 6 years ago.
#include <iostream>
using namespace std;
int ROWS = 3;
int COLS = 4;
How do I solve this c++ multidimensionalArray problem? I have been working on this for some time but I just cant figiure it out, thank you verry much
void fillScores(int [ROWS][COLS]);
int main() {
int scores[ROWS][COLS] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
fillScores(scores);
return 0;
}
void fillScores(int newScores[ROWS][COLS]) {
cout << newScores[1][1]<<endl;
}

You can wrap the array in a struct and then pass it by address, where you need.
struct ArrayWrapper
{
int _arr[ROWS][COLS];
};

Related

Size of parameter array in funtion [duplicate]

This question already has answers here:
When a function has a specific-size array parameter, why is it replaced with a pointer?
(3 answers)
Using sizeof on arrays passed as parameters [duplicate]
(3 answers)
Closed 1 year ago.
#include<iostream>
#include <vector>
using namespace std;
int size_f(vector<int> adj[])
{
return sizeof(adj);
}
int main()
{
vector<int> adj[] = {{0, 1}, {0, 2}, {1, 2}, {2, 3}};
cout << sizeof(adj) << endl;
cout << size_f(adj);
}
96
8
This is my program and its result. I don't understand why size_f return 8. Can you explain it for me? And how can I know size of array that is parameter of my funtion. Thank you.

How to get size of const array in c++? [duplicate]

This question already has answers here:
getting size of array from pointer c++
(6 answers)
Closed 1 year ago.
#include <iostream>
using namespace std;
const int triTable[4][6] = {
{},
{0, 8, 3},
{0, 1, 9},
{1, 8, 3, 9, 8, 1},
};
int main() {
const int *f = triTable[3];
int size = sizeof(f)/sizeof(*f);
cout << size;
}
This gives me wrong numbers. It should print 6. How can I get it?
How to get size of const array in c++?
Like this:
std::size(triTable[3])
This gives me wrong numbers.
You generally cannot get the size of an array by using a pointer to element of that array.
As stated sizeof f is the size of the pointer not the size of the object where it points to, as also said, using STL containers is a much better option given that they have size members that keep track of the size of the container.
That being said, if you're adamant in using a C style array, a solution would be to wrap it in a struct or class and return the size from there, i.e:
struct myArray
{
const int triTable[4][6] = {
{},
{0, 8, 3},
{0, 1, 9},
{1, 8, 3, 9, 8, 1},
};
const int size = std::size(triTable[3]); // size data member
int arraySize() const{
return std::size(triTable[3]); // size method
}
};
int main()
{
myArray a;
std::cout << a.size << "\n";
std::cout << a.arraySize();
}
Output:
6
6

How to make space between array values in printing?

I'm interested, how could i get same result in C++. For this C code:
for(i=0;i<n;i++)
printf("%4d",array[i]);
This will create 4 space gap between my values from array.
Is there something similar in C++?
The same code works in C++:
const int n = 10;
int array[n] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (int i=0;i<n;i++)
printf("%4d",array[i]);
But if you're looking for more a C++-esque way of doing things, you can use std::cout and std::setw:
#include <iostream> // cout
#include <iomanip> // setw
int main()
{
int array[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (auto n : array)
{
std::cout << std::setw(4) << n;
}
}

Why I am getting random values from array in a function when returning an array from a function as an argument? [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 6 years ago.
I wanted to pass an array by reference in a function from another function. Here is my code below
// Objectives:
// 1. Passing an array to a method
// 2. Returning arrays from a method
#include <iostream>
using namespace std;
int getArray(int* arr) {
for (int i=0; i< 11; i++) {
cout << arr[i] << endl;
}
return 0;
}
int* returnArray() {
int arr [11] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21};
return arr;
}
int main() {
getArray(returnArray());
return 0;
}
Here is my output:
get_return_array.cpp:17:12: warning: address of stack memory associated with local variable 'arr' returned
[-Wreturn-stack-address]
return arr;
^~~
1 warning generated.
1
32767
170167402
1
9
11
2051556088
32767
17
9
1436251616
Why values of array are some garbage values and what does the warning signifies?
Marked as duplicate, why??: I have shown usage of static with explanation while the others' answer haven't.
C++ does not advocate the passing reference of local array to outside function. Lifetime of arr is till it's parent function runs. The values in the stack of arr will be overwritten if any new assignment is done.
So to overcome this restriction we have to use static whose purpose is to allocate values statically so that its lifetime extends till program runs.
That's why array has some garbage values.
The correct program will be
#include <iostream>
using namespace std;
int getArray(int* arr) {
for (int i=0; i< 11; i++) {
cout << arr[i] << endl;
}
return 0;
}
int* returnArray() {
static int arr [11] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21};
return arr;
}
int main() {
getArray(returnArray());
return 0;
}
It's corresponding output is:
1
3
5
7
9
11
13
15
17
19
21
Cheers

How do I stop my array from printing address?

I have a header, cpp and main class.
//Arr.h
class Arr
{
public:
void setArr();
void printArr();
private:
int x[5];
};
//Arr.cpp
#include "Arr.h"
#include <iostream>
using namespace std;
void Arr::setArr()
{
int x[5] = { 2, 3, 5, 7, 11 };
}
void Arr::printArr()
{
for (int i = 0; i < 5; i++)
{
cout << x[i] << "\n";
}
}
//main.cpp
int main()
{
Arr a;
a.setArr();
a.printArr();
}
However, when I run the code, a.printArr() prints out array address and not the values contained in the array. Is there a way to fix this?
Your code will print not address but some indeterminate value generated via default-initializing. Initialize the member array instead of the local array to throw away.
void Arr::setArr()
{
x[0] = 2;
x[1] = 3;
x[2] = 5;
x[3] = 7;
x[4] = 11;
}
Your problem is here:
void Arr::setArr()
{
int x[5] = { 2, 3, 5, 7, 11 };
}
the declaration int x[5] defines a new array of 5 elements which will be destroyed on exiting that function; and the name x hides the data member Arr::x.
One way you can do it is this:
void Arr::setArr()
{
/*static*/ auto arr = { 2, 3, 5, 7, 11 };
std::copy(arr.begin(), arr.end(), x);
}
Full code:
#include <iostream>
#include <algorithm>
class Arr
{
public:
void setArr();
void printArr();
private:
int x[5];
};
using namespace std;
void Arr::setArr()
{
/*static*/ auto arr = { 2, 3, 5, 7, 11 };
std::copy(arr.begin(), arr.end(), x);
}
void Arr::printArr()
{
for (int i = 0; i < 5; i++)
{
cout << x[i] << "\n";
}
}
//main.cpp
int main()
{
Arr a;
a.setArr();
a.printArr();
}
Your code is not printing array address. Maybe you saw some unexpected numbers and assumed it was an address, but in fact it is undefined behaviour caused by outputting uninitialized variables.
Your code int x[5] = .... failed because this declares a new local variable x, it doesn't modify the class member x.
Perhaps you tried:
x = { 2, 3, 5, 7, 11 };
and got compilation errors. This is because C-style arrays may not be assigned. This annoying rule is a hangover from C++'s past. To avoid this problem and many others, you can try to avoid using C-style arrays. In this case use a C++ array:
private:
std::array<int, 5> x;
Then the suggested assignment will work.
As WhiZTiM has already pointed out, your problem is at the setArr function in your class. The reason for this is because in C++ you cannot assign values to the array in the "normal fashion" i.e. using x = {blah, blah, blah}; (unless you use std::array<int, ARRAYSIZE>). In setArr you are creating another array named x and then this array is deleted once it is out of scope, and in printArr you are printing an array with no values in it yet.
Each value in the array must be set individually in C styled arrays (as shown in MikeCAT's answer).
One solution to this is to create a temporary array with the values you want and assigning the values to your class array through a for loop, i.e.:
void Arr::setArr() {
const int ARRAYSIZE = 5;
int tmp[ARRAYSIZE] = {2, 3, 5, 7, 11};
for (int i = 0; i < ARRAYSIZE; ++i) {
x[i] = tmp[i];
}
}
As M.M also pointed out, can simply change int x[5] in your private variables in Arr to std::array<int, 5> x and then in setArr simply have the statement: x = {2, 3, 5, 7, 11}; which is the better option in my opinion and easier to read, but it's also good to know how to use C arrays 😊