I have a program where I want to pass an array - in this case k[arrsize], which is a parameter of the funciton fillArray() to the other function create_file() (the same array, filled with the random numbers). However, I cannot pass the same array and I would like to ask how can this be done?
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <time.h>
#include <stdlib.h>
using namespace std;
const int arrsize = 20;
//int a[arrsize];
fstream p;
void fillArray(int k[arrsize])
{
srand((unsigned)time(NULL));
for (int i = 0; i<20; i++)
{
if (i % 2 == 0)
{
k[i] = -(rand() % 100);
}
else
{
k[i] = (rand() % 100);
}
}
}
void create_file(int k[arrsize])
{
p.open("danni.dat", ios::out);
for (int i = 0; i<20; i++)
{
p << k[i] << endl;
}
p.close();
}
int main() {
fillArray(k);
create_file(k);
return 0;
}
You simply forget to define an array:
int main() {
int k[arrsize];
fillArray(k);
create_file(k);
}
Usually you don't want to pass the whole array, instead you might want to pass a reference to it. I suggest you to use std::array instead of a C-style arrays.
#include <array>
void fill(std::array<int, 1>& a)
{
a[0] = 0;
}
int main()
{
std::array<int, 1> a = {};
fill(a);
return 0;
}
Related
I have a bit of a problem with this. I've tried to create a function to return a random number and pass it to the array, but for some reason, all the numbers generated are "0".
#include <iostream>
#include <ctime>
#include <iomanip>
using namespace std;
int generLosNum(int);
int main()
{
srand(time(NULL));
int LosNum;
const int rozmiar = 10;
int tablica[rozmiar];
for(int i=0; i<rozmiar; i++)
{
tablica[i] = generLosNum(LosNum);
cout << tablica[i] <<" ";
}
return 0;
}
int generLosNum(int LosNum)
{
int LosowyNum;
LosowyNum = (rand() % 10);
return (LosNum);
}
So the return for your int generLosNum(int LosNum) was printing 0 because you had it returning LosNum which was initialized equaling to zero. I changed your code so it works and will print out the 10 random numbers.
#include <iostream>
#include <ctime>
#include <iomanip>
using namespace std;
int generLosNum();
int main()
{
srand(time(NULL));
int LosNum = 0;
const int rozmiar = 10;
int tablica[rozmiar];
for (int i = 0; i < rozmiar; i++)
{
tablica[i] = generLosNum();
cout << tablica[i] << " ";
}
return 0;
}
int generLosNum()
{
int LosowyNum;
LosowyNum = (rand() % 10);
return LosowyNum;
}
Change your method generLosNum to the following and the method signature to int generLosNum() and it should work.
int generLosNum()
{
return (rand() % 10);
}
Reason: As others also mentioned in the comments, you were just returning the number that you passed in as parameter and also the logic for this method doesn't even need a parameter.
I tried to write a simple code to calculate an array elements' sum. every thing looks normal but the function return the sum value wrongly (it always multiply it by two). Although if I want just print the value, it works fine.
this is the code:
#include <iostream>
using namespace std;
void getElements(int[],int);
int sumOfElements(int[],int);
int number;
int sum=0;
int main()
{
int a[10];
getElements(a,5);
sumOfElements(a,5);
cout<<"The sum is "<<sumOfElements(a,5)<<endl;
return 0;
}
//Getting array's elements
void getElements(int numbers[],int size_)
{
for (int i=0; i<size_; i++)
{
cout<<"numbers["<<i<<"]: ";
cin>>number;
numbers[i]=number;
}
cout<<'\n';
}
//Calculation the sum of array's elements
int sumOfElements(int numbers[],int size_)
{
for(int i=0;i<size_;i++)
{
sum+=numbers[i];
}
cout<<sum<<endl;
return sum;
}
any idea? thank you in advance!
You defined int sum globally and were calling sumOfElementstwice, so sum contained twice what you expected.
Here is a modified version of your code that does what you want:
#include <iostream>
using namespace std;
void getElements(int[], int);
int sumOfElements(int[], int);
int main() {
int numbers[5];
getElements(numbers, 5);
cout << sumOfElements(numbers, 5);
return 0;
}
void getElements(int numbers[], int size) {
for (int i = 0; i < size; i++) {
cin >> numbers[i];
}
}
int sumOfElements(int numbers[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += numbers[i];
}
return sum;
}
Here is a modified and simpler version of your program:
#include <array>
#include <iostream>
#include <numeric>
using namespace std;
int main(){
const int num_elements_to_sum = 5;
array<int, num_elements_to_sum> elements;
for(int i=0; i<num_elements_to_sum; ++i){
cin>>elements[i];
}
int sum = accumulate(elements.begin(), elements.end(), 0);
cout<<"Sum: "<<sum<<endl;
return 0;
}
C++ has a dedicated fixed size array container, use this instead of C-style arrays. This then allows to use standard library algorithms instead of your own implementation (e.g. accumulate).
I couldn't figure out how to make a function return an array so instead I decided to try and pass an empty array (of the correct size) into my function and than reassign the address to a different array of the same size. Is this at all a way to do things??? Can someone show me what to do? if this is wrong can you fill me in on how to do this?
here is my code:
#include <iostream>
#include <cmath>
using namespace std;
void ArrayFiller(int earray,int s, int f){
int *ptrarray = &earray;
int prenum_size = std::abs(s) + f - 1;
int pre_num[prenum_size];
for(int x=s;x<f;x++){
pre_num[x+std::abs(s)] = x;
}
*ptrarray = pre_num;
}
int Main(){
int first = -10;
int second = 15;
int temp[abs(first) + abs(second)];
ArrayFiller(temp, first, second);
int n = sizeof(temp)/sizeof(temp[0]);
for (int i = 0; i < n; i++) {
cout << temp[i] << ' ';
}
return 0;
}
I think you're looking for something like this:
#include <iostream>
#include <cmath>
using namespace std;
void ArrayFiller(int earray[],int s, int f){
for(int x=s;x<f;x++){
earray[x+(std::abs(s))] = x;
}
}
int main(){
int first = -10;
int second = 15;
int n = abs(first)+abs(second);
int* temp = new int[n];
ArrayFiller(temp, first, second);
for (int i = 0; i < n; i++) {
cout << temp[i] << ' ';
}
delete [] temp;
return 0;
}
I'm new/noob programmer of C++, and I've this problem. I want to pass a pointer of double to a function (which will process some data on it) and read (after the process) a fixed value of that "array". I've do this:
void ReadDoubles(double* samples, int size)
{
for (int i=0; i < size; ++i)
{
*samples = i*10.1;
samples++;
}
}
int main()
{
int size = 10;
double *values=0;
ReadDoubles(values, size);
cout << *(values+3);
}
BUt of course it seems I can't init the pointer that way. I think I need to init the pointer allocating 10 values? Tried:
double *values[size];
but that's not the solution. How would you do this simple task?
You need to allocate the array at first. Here you are
#include <iostream>
void ReadDoubles( double* samples, size_t size )
{
for ( size_t i = 0; i < size; ++i )
{
*samples = i*10.1;
samples++;
}
}
int main()
{
size_t size = 10;
double *values = new double[size];
// ^^^^^^^^^^^^^^^^
ReadDoubles( values, size );
std::cout << *(values+3) << std::endl;
delete []values;
}
The program output is
30.3
If you don't want to use the operator new then there are two general approaches. Either you can declare an array as for example
int main()
{
const size_t size = 10;
//^^^^
double values[size];
// ^^^^^^^^^^^^
ReadDoubles( values, size );
std::cout << *(values+3) << std::endl;
}
or you can use standard class std::vector<double>.In this case the function should be rewritten appropriately.
For example
#include <iostream>
#include <vector>
void ReadDoubles( std::vector<double> &samples, size_t size )
{
samples.resize( size );
for ( size_t i = 0; i < size; ++i )
{
samples[i] = i*10.1;
}
}
int main()
{
size_t size = 10;
std::vector<double> values;
ReadDoubles( values, size );
std::cout << values[3] << std::endl;
}
If you are not allowed to change the RealDoubles function and you must have a function return the size then the following should work:
#include <string>
#include <iostream>
#include <math.h>
#include <cmath>
using namespace std;
void ReadDoubles(double* samples,int size)
{
for (int i=0; i < size; ++i) {
*samples = i*10.1;
samples++;
}
}
int get_size()
{
return 10;
}
int main()
{
int size = get_size(); // get size from function
//double *values=0;
double *values = new double[size] {0}; // Use new to allocate array. Optional: use {0} to init first element to 0, others default initialized to 0
ReadDoubles(values,size);
cout << *(values+3);
delete[] values;
}
If you prefer to avoid new and delete then you can let a std::vector manage the container for you:
#include <string>
#include <iostream>
#include <math.h>
#include <cmath>
#include <vector>
using namespace std;
void ReadDoubles(double* samples,int size)
{
for (int i=0; i < size; ++i) {
*samples = i*10.1;
samples++;
}
}
int get_size()
{
return 10;
}
int main()
{
int size = get_size(); // get size from function
//double *values=0;
std::vector<double> value_container(size,0); // vector will do the new and delete for us
double *values = value_container.data();
ReadDoubles(values,size);
cout << *(values+3);
} // vector destructor will do delete when it goes out of scope
I've got this code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> *vecptr;
int veclen;
void getinput()
{
string temp;
for(int i = 0; i < 3; i++)
{
cin>>temp;
vecptr->push_back(temp);
}
veclen = vecptr->size();
}
int main()
{
getinput();
for(int i = 0; i < veclen; i++)
{
cout<<vecptr[i]<<endl;
}
return 0;
}
My compiler(G++) throw me some errors: test2.cpp:28:17: error: no match for 'operator<<' in 'std::cout << *(vecptr + ((unsigned int)(((unsigned int)i) * 12u)))' ...
What's wrong? What can I do to fix it?
The program is still not completely right. You have to initialize the vector pointer and then give it a size and the use it. A full working code could be,
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> *vecptr = new vector<string>(10);
int veclen;
void getinput()
{
string temp;
for(int i = 0; i < 3; i++)
{
cin>>temp;
(*vecptr)[i] = temp;
}
veclen = (*vecptr).size();
}
int main()
{
getinput();
for(int i = 0; i < veclen; i++)
{
cout<<(*vecptr)[i]<<endl;
}
return 0;
}
Although I have mentioned the size as 10 you could make it a variant.
You need to dereference vecptr here to get the underlying vector:
cout << (*vecptr)[i] << endl;
You will also need to initialize vecptr.