I'm trying to pass a matrix without dimensions to a function and fill with data. Here is an example:
#include <iostream>
#include <stdlib.h>
using namespace std;
void fun(double **matrix);
int main(void)
{
double **matrix;
fun(matrix);
for(int i = 0; i < 10; i ++)
{
cout << "matrix = " << matrix[i][0] << "\t" << matrix[i][1] << endl;
}
}
void fun(double **matrix)
{
int rowCount = 10;
int colCount = 2;
matrix = new double*[rowCount];
for(int i = 0; i < rowCount; ++i)
matrix[i] = new double[colCount];
for(int i = 0; i < rowCount; i ++)
{
matrix[i][0] = 3.;
matrix[i][1] = 4.;
}
}
It compiles but when I execute it, it return the following error:
Illegal instruction: 4
Do you know why?
First of all if you are got a pointer it should point at something, so in order to not have a warnings just initialize it with nullptr. Second thing is that you should return a pointer to pointer.I fixed your code so you can look what you have made wrong,
#include <iostream>
#include <stdlib.h>
using namespace std;
double **fun(double **matrix);
int main(void)
{
double **matrix= nullptr;
matrix = fun(matrix);
for (int i = 0; i < 10; i++)
{
cout << "matrix = " << matrix[i][0] << "\t" << matrix[i][1] << endl;
}
getchar();
getchar();
}
double **fun(double **matrix)
{
int rowCount = 10;
int colCount = 2;
matrix = new double*[rowCount];
for (int i = 0; i < rowCount; ++i)
matrix[i] = new double[colCount];
for (int i = 0; i < rowCount; i++)
{
matrix[i][0] = 3.;
matrix[i][1] = 4.;
}
return matrix;
}
Your program fails because fun allocates memory, but does not return the newly allocated matrix array to main. It would be easier to do this by return value than by argument:
double** fun() {
// ...
double** matrix = new double*[...];
// ...
return matrix;
}
int main() {
double** matrix = fun();
// ...
}
There are a million other ways to do that (by passing a double*** into fun, or a reference, or by using some sort of object etc). Pick whatever you like best.
Related
I'm fairly new to programming and was trying to create a program which creates a one dimensional array with random numbers from a certain range and then prints it out. I managed to make a function to create the array but I'm having trouble actually printing out the array I made. I have a general idea of what the problem might be but no clue as to how to fix the code.
Here is the code in question:
#include <iostream>
using namespace std;
int *create(int n)
{
int *arr = new int [n];
for (int i = 0; i > n; i++)
{
arr[i] = rand() % 100;
}
}
int main ()
{
int n = 12;
int *arr = create(n);
cout << "this is the array: ";
for (int i = 0; i > n; i++)
{
cout << arr[i] << " ";
};
delete[] arr;
return 0;
}
There are two errors in your code:
You are not returning your array from create()
Your loop condition is incorrect.
Fixed code:
#include <iostream>
using namespace std;
int *create(int n)
{
int *arr = new int [n];
for (int i = 0; i < n; i++)
{
arr[i] = rand() % 100;
}
return arr;
}
int main ()
{
int n = 12;
int *arr = create(n);
cout << "this is the array: ";
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
};
delete[] arr;
return 0;
}
I dont see how you code compiles.
You are not returning anything from function.
both your loop conditions should be <n
This way is works but your design is very poor, unless you are just learning handling pointers.
#include <iostream>
using namespace std;
int* create(int n)
{
int* arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = rand() % 100;
}
return arr;
}
int main()
{
int n = 12;
int* arr = create(n);
cout << "this is the array: ";
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
};
delete[] arr;
return 0;
}
The only missing part in your code - you are not returning your arr variable from your create function.
int *create(int n)
{
int *arr = new int [n];
for (int i = 0; i > n; i++)
{
arr[i] = rand() % 100;
}
return arr;
}
This way it will work:)
You made a mistake in the loop. you used '>' instead of '<' line 22 should be.
for (int i = 0; i < n; i++)
The loop stopped before the first iterations because i=0 was smaller than n=12.
I am having trouble with the push_back() function in C++. For a reason which I don't understand, the push_back function will "not accept" the value I am telling it to append, but the code works perfectly until I try to display the values I want (end of code). I have checked the value type, which is double, but it still won't append it.
The value I am trying to insert comes from a function which calculates the mean of a vector, taking out the NaN values. The code works perfectly but when I am trying to display the values I want, I always get: Segmentation fault (core dumped).
This mean function first iterates over a range and creates a vector in which the NaN will be taken away. Then the mean will be calculated. I have spent quite some time on trying to figure out where the error could come from but wasn't able to figure out anything so any help would be highly appreciated. The following mean function:
double mean_func(double **arr, int iterations, int header, int start){
std::vector<double> vec;
for (int i=start-iterations; i < start; i++){
vec.push_back(arr[i][header]);
}
vec.erase(std::remove_if(std::begin(vec),
std::end(vec),
[](const auto& value) { return std::isnan(value); }),
std::end(vec));
double sum = std::accumulate(vec.begin(), vec.end(), 0.0);
double mean = sum / vec.size();
return mean;
}
The whole code where transf_array_2_vec transforms a vector to an array.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <omp.h>
#include <cmath>
#include <vector>
#include <algorithm>
#include <iostream>
#include <numeric>
#include <typeinfo>
double** transf_vec_2_array(std::vector<std::vector<double> > vals, int N, int M)
{
double** temp;
temp = new double*[N];
#pragma omp parallel for
for(int i=0; (i < N); i++)
{
temp[i] = new double[M];
for(int j=0; j < M; j++)
{
temp[i][j] = vals[i][j];
}
}
return temp;
}
double mean_func(double **arr, int iterations, int header, int start){
std::vector<double> vec;
for (int i=start-iterations; i < start; i++){
vec.push_back(arr[i][header]);
}
vec.erase(std::remove_if(std::begin(vec),
std::end(vec),
[](const auto& value) { return std::isnan(value); }),
std::end(vec));
double sum = std::accumulate(vec.begin(), vec.end(), 0.0);
double mean = sum / vec.size();
return mean;
}
double** cfun(double **indata, unsigned int rows, unsigned int cols, int max_inputs, int daily_inputs, int weekly_inputs, int inputs_short_term, const char **header_1, const char **header_2, unsigned int size_header_1, unsigned int size_header_2, double **outdata) {
std::vector< std::vector <double>> seq_collec;
std::vector<double>seq;
unsigned int i, j, k, l;
unsigned int temp= 5080;
int num = omp_get_thread_num();
omp_set_num_threads(num);
//#pragma omp parallel for //private(seq)
for(i = max_inputs + weekly_inputs; i < temp ; i++) {
for(j = 0; j < size_header_1; j++ ){
for(k = 0; k < size_header_2 ; k++){
for(l = i-max_inputs; l < i; l++){
if((strcmp(header_2[k],"price")==0)|| (strcmp(header_2[k], "change")==0)){
seq.push_back(indata[l][j+k]);
seq.push_back(mean_func(indata, inputs_short_term, j*size_header_2, l));
//std::cout << i << " " << j << " " << k <<std::endl;
//std::cout << header_1[j] << " " << header_2[k] << std::endl;
//std::cout << typeid(mean).name() << std::endl;
//std::cout << mean_func(indata, inputs_short_term, j*size_header_2, l) << std::endl;
}else{
seq.push_back(indata[l][j+k]);
//std::cout << header_1[k] << " " << header_2[k] << std::endl;
}
}
}
seq.push_back(mean_func(indata, daily_inputs, j+k, l));
seq.push_back(mean_func(indata, weekly_inputs, j+k, l));
}
//std::cout << seq.size() << std::endl;
seq_collec.push_back(seq);
seq.clear();
}
outdata = transf_vec_2_array(seq_collec, seq_collec.size(), seq_collec[0].size());
//std::cout << seq_collec.size() << std::endl;
//std::cout << seq_collec[0].size() << std::endl;
return outdata;
}
int main(){
int rows = 10846, cols = 12, max_inputs = 20, daily_inputs = 1000, weekly_inputs=5000, inputs_short_term=4;
unsigned int size_header_1 = 3, size_header_2 = 4;
const char *header_1[size_header_1] = {"CH:SMI","DJIA","RUI"};
const char *header_2[size_header_2] = {"change","delta_vol","price","volume"};
double* *indata = new double*[rows];
double* *outdata = new double*[rows];
for (int i=0; i < rows; i++){
indata[i] = new double[cols];
outdata[i] = new double[cols];
}
for (int i=0; i < rows; i++){
for (int j=0; j < cols; j++){
indata[i][j]=i + j ;
}
}
outdata = cfun(indata, rows, cols, max_inputs, daily_inputs, weekly_inputs, inputs_short_term, header_1, header_2, size_header_1, size_header_2, outdata);
for(int j = 0; j < 1; j++){
for(int i = 0; i < 366; i++){
std::cout << outdata[i][j] << std::endl; // PROBLEM HERE !!!
}
}
return 0;
}
My code works fine when the file Im reading from only contains ints, but when I have floats in the file it doesnt seem to work, for example if I have 1.5 in the file it will only read it as 1 and it wont read any of the numbers after it.
Anyone knows whats causing this? The dynamic array where everything is saved in is a float so Im not sure what to do at this point
#include <iostream>
#include <fstream>
#include <string>
float *allocateArray(std::string fileName, int &arraySize, int &counter)
{
int a = 0;
std::ifstream myReadFile;
myReadFile.open(fileName);
float *arr = new float[arraySize]{0.0};
while (myReadFile >> a)
{
counter++;
if(counter == arraySize)
{
arr[arraySize -1] = a;
}
else
{
float *tempArray = new float[arraySize +1]{0.0};
for(int i = 0; i < arraySize; i++)
{
tempArray[i] = arr[i];
}
delete[] arr;
arraySize++;
arr = new float[arraySize];
for(int x = 0; x < arraySize; x++)
{
arr[x] = tempArray[x];
}
arr[arraySize-1] = a;
}
}
myReadFile.close();
return arr;
}
void output(float *arr, int arraySize,int counter)
{
float sum = 0.0;
for(int x = 0; x < arraySize; x++)
{
sum += arr[x];
}
float average = sum/counter;
std::cout << "Output: ";
for(int i = 0; i < arraySize; i++)
{
if(arr[i] > average)
{
std::cout << arr[i] << " ";
}
}
}
int main()
{
int arraySize = 1;
int counter = 0;
float *arr = allocateArray("input.in", arraySize, counter);
std::cout << "Input: ";
for(int x = 0; x < arraySize; x++)
{
std::cout << arr[x] << " ";
}
output(arr, arraySize, counter);
getchar();
return 0;
}
I have already wrote this code but it does not work correctly if I entered negative values in the array. What should I do ?!!
#include <iostream>
using namespace std;
void maxRow(int arr[][2],int row) {
for (int i = 0; i < row; i++) {
int valueMax = arr[i][0];
for (int j = 0; j < 2; j++) {
if (arr[i][j] > valueMax) {
valueMax = arr[i][j];
cout << valueMax << endl;
}
}
}
}
int main() {
int numbers[6][2] = {1,10,5,6,7,8,19,89,-2,17,-3,-7};
maxRow(numbers, 6);
}
You're cout should be outside the inner for loop. In your example the second element in each row is the larger one and hence the code might seem to work.
Is this right ??
#include <iostream>
using namespace std;
void maxRow(int arr[][2],int row) {
for (int i = 0; i < row; i++) {
int valueMax = arr[i][0];
for (int j = 0; j < 2; j++) {
if (arr[i][j] > valueMax) {
valueMax = arr[i][j];
}
}
cout << valueMax << endl;
}
}
int main() {
int numbers[3][2] = {{1,2}, {19, 2}, {-2, -5}};
maxRow(numbers, 3);
}
You can use std::max_element in a loop, where each iteration stores the greater of either the current maximum, or the return of std::max_element.
#include <iostream>
#include <climits>
#include <algorithm>
void maxRow(int arr[][2],int row)
{
int curMax = INT_MIN;
for (int i = 0; i < row; i++)
{
curMax = std::max(curMax,
*std::max_element(&arr[i][0], &arr[i][2]));
}
std::cout << curMax;
}
int main() {
int numbers[6][2] = {1,10,5,6,7,8,19,89,-2,17,-3,-7};
maxRow(numbers, 6);
}
Live Example
I would like to point out some random integers using the regular print function, then print again the same integers using pointer notation. When I use pointer notation I run into some trouble. If anyone could send some tips it'd be much appreciated. If i comment out a specific line of code, the program will compile completely, but not with the outputs I'd like.
#include <iostream>
#include <ctime>
#include <stdlib.h> //srand(), rand()
using namespace std;
void printArray(int[], int);
//void printToday(int , );
int main()
{
int i = 0;
const int SZ = 100;
int myArray[SZ] ={0};
srand(time(0));
int myArrayTotal = 0;
int *thelight;
thelight = myArray;
for (int i = 0; i <=100; i++)
{
myArray[i]= i+rand()%1000 ;
}
cout << "Array Notation:\n\n";
printArray(myArray, SZ);
system("pause");
system("cls");
cout << "Pointer Notation: \n\n";
int k = 0;
for (int i = 0; i < 10; ++i)
{
for (int j = 0; j < 10; ++j)
{
cout<< *(thelight + k)<< "\t";
++k; //if I comment out this line the second part of the program will run, but it isn' the values I want.
} cout<< endl;
}
}
void printArray(int ArrayName[], int ArraySize)
{
int k = 0;
for (int i = 0; i < 10; ++i)
{
for(int j = 0; j < 10 ; ++j)
{
cout << ArrayName[k] << "\t";
++k;
}cout << endl;
}
}
Thank you