This question already has answers here:
Returning a reference to a local variable in C++
(3 answers)
Closed 8 years ago.
Trying to make a program that sums 5 digit numbers by each digit. For some reason when I attempt to print individual elements of an array (one element at a time running 5 times) I get the correct value of 69134. But when I print them together:
int *addArray(int arr1[], int arr2[]){
int arrSum[5];
int r=0;
for(int i=4; i>=0; i--){
arrSum[i]=(arr1[i]+arr2[i]+r)%10;
r=((arr1[i]+arr2[i]+r)>=10);
}
return arrSum;
}
int main(){
using namespace std;
int data1[5]={1,2,3,4,5};
int data2[5]={5,6,7,8,9};
int *arrSum=addArray(data1,data2);
cout << arrSum[0] << arrSum[1] << arrSum[2] << arrSum[3] << arrSum[4];
return 0;
}
I end up with the result 60000. Anyone know what is going on?
In addArray you are returning a pointer to a local variable (arrSum), which results in undefined behaviour. You should either pass in the result array from the calling function, or allocate the array dynamically. For example, using the first approach:
void addArray(const int arr1[], const int arr2[], int arrSum[])
{
int r=0;
for(int i=4; i>=0; i--)
{
arrSum[i]=(arr1[i]+arr2[i]+r)%10;
r=((arr1[i]+arr2[i]+r)>=10);
}
}
int main()
{
int data1[5]={1,2,3,4,5};
int data2[5]={5,6,7,8,9};
int arrSum[5];
addArray(data1,data2,arrSum);
cout << arrSum[0] << arrSum[1] << arrSum[2] << arrSum[3] << arrSum[4];
return 0;
}
Related
This question already has answers here:
Passing Arrays to Function in C++
(5 answers)
What is array to pointer decay?
(11 answers)
Closed 7 months ago.
What is the difference between taking as a function argument an int pointer or an int array in C++?
void arrayFunction1(int * x) {
for(int i = 0; i < 10; i++) {
cout << x[i] << endl;
}
}
void arrayFunction2(int x[]) {
for(int i = 0; i < 10; i++) {
cout << x[i] << endl;
}
}
int main() {
int dstdata[10];
arrayFunction1(dstdata);
arrayFunction2(dstdata);
return 0;
}
Both results look the same to me.
There are completely identical. In a function parameter int x[] is just another way of writing int* x. Even int x[10] is the same (the 10 is completely ignored).
Now why Kernighan and Ritchie (the inventors of C) thought this piece of deception was a good idea is another question. I guess they weren't thinking of all the people who have to learn the syntax.
This question already has answers here:
Passing a 2D array to a C++ function
(17 answers)
Variable length arrays (VLA) in C and C++
(5 answers)
Closed 3 months ago.
I am trying to pass a 2D array to a function but I am failing to do so. There is no problem with passing 1D array. How can I do this?
#include <iostream>
using namespace std;
void DisplayBoard(int matrix[],int n) // Prints out the given array.
{
for (int j = 0; j < n; j++)
{
cout << matrix[j];
}
}
int main()
{
int n,m;
cin>>n;
//int matrix[n]={};
DisplayBoard(matrix,n);
return 0;
}
i think you want to input index number (n) from user and then input array object from user too
i complete your code like this :
#include <iostream>
using namespace std;
void DisplayBoard(int matrix[],int n) // Prints out the given array.
{
cout<<endl ;
for (int j = 0; j < n; j++)
{
cout << matrix[j]<<" ";
}
}
int main() {
int n,m;
cin>>n ;
int matrix[n];
for(int i=0;i<n;i++) {
cin>>matrix[i];
}
DisplayBoard(matrix,n);
return 0;
}
remember to declare array in main function too ,
that was one of your code error !
and this is incorrect to declare array :
int matrix[n]={} // incorrect !
Well. int matrix[n]={}; fills it with zeros and that's what I wanted to do. And my code with 1D array works fine but if I do it like so it does not.
#include <iostream>
using namespace std;
void DisplayMatrix(int matrix[][],int n,int m)
{
for(int i=0;i<n;i++)
{
for (int j = 0; j < m; j++)
{
cout << matrix[j];
}
}
}
int main()
{
int n,m;
cin>>n>>m;
int matrix[n][m]={};
DisplayMatrix(matrix,n,m);
return 0;
}
I need some help here please.
I just started learning C++ (coming from Python background).
I'm trying to familiarize myself with arrays and functions. Wrote a bunch of functions to do as stated, above each one.
However, the function which is supposed to sum elements in an array and return their sum, seem to be adding 10 to the result, no matter the argument supplied as input. What am I doing wrong please, as I can't seem to find this out. Any help on general layout of my code also would be appreciated.
// WORKING WITH ARRAYS AND FUNCTIONS
#include<iostream>
using namespace std;
// FUNCTION TO INSTANTIATE ARRAY INT OF LENGTH N.
int* array_creator(int n)
{
static int ary_of_ten[10]; //declare array
for (int i=0; i<n; i++) //use loop to fill it up
{
ary_of_ten[i] = i+1;
}
return ary_of_ten;
}
//FUNCTION TO PRINT ARRAY ELEMENTS
void* array_printer(int arr[], int array_lenght)
{
for (int i=0; i<array_lenght-1; i++)
{
cout << arr[i] << " ";
}
cout << arr[array_lenght-1] << endl;
}
//FUNCTION ACCEPTS INT ARRAYS AND RETURNS ARRAY OF SQUARE OF EACH ELEMENT
int* square_array(int *p, int array_length)
{
const int ary_sz(array_length);
static int sqd_values[10];
for (int i=0; i<ary_sz; i++)
{
*(sqd_values + i) = *(p+i) * *(p+i);
}
return sqd_values;
}
//FUNCTION ACCEPTS INT ARRAYS AND RETURNS SUM OF ITS ELEMENTS
int sum_array(int *arry, int array_length)
{
int summation;
for(int i=0; i<array_length; i++)
{
summation += *(arry + i);
}
return summation;
}
int main()
{
cout << sum_array(array_creator(10), 3) << endl;
array_printer(array_creator(10), 10); //print array of 1-10 elements
array_printer(square_array(array_creator(10), 10), 10); //prt arry of sqrd values
return 0;
}
summation shuld be initialized to 0.
int summation=0;
My problem is that I have trouble calling the int computePattern method in int main(). I am able to use the insertNumber method. But i don't know how to use the computePattern method. The method is to compute the number of patterns and return the count. The pattern is that both adjacent numbers must be greater than 7. Hence, there are only 5 pairs to check as there are 10 numbers. For now the output is only the random arrays which worked, but I need to print out the number of patterns too. I need to use methods as it is required in the question.
int insertNumber(int b )
{
int a = rand()%10+1;
return a;
}
int computePattern(int* inArray, int size )
{
int patterns=0;
for(int z=0;z<size;z=z+2)
{
if(inArray[z]+inArray[z+1]>7)
{
patterns ++ ;
}
}
return patterns;
}
int main()
{
int arrays[10];
srand(time(0));
for ( int b=0; b<10 ; b++)
{
arrays[b] = insertNumber(b);
}
cout << "Arrays";
for ( int c= 0; c<10; c++)
{
cout << " " ;
cout << arrays[c];
}
int patterns =computePattern(arrays,10);
cout<<endl;
cout << "Patterns" <<patterns;
}
The array in computePattern remains uninitialised. Ergo, it will contain random variables in the memory which will mess up your computational path.
You should maybe modify the function to int computePattern(int z, int array[]). Then pass the array from the main scope.
You have different arrays in main than in computePattern. Just because they share a name doesn't mean they're the same variable. Each one of them is function scope. A better way is to pass in the address and size of the array.
int computePattern(int* inArray, int size)
{
int patterns=0;
for(int z=0; z<size-1; z+=2)
{
if((inArray[z] + inArray[z+1]) > 7)
{
patterns++;
}
}
return patterns;
}
//... then in main...
int patterns=computePattern(arrays, 10);
cout << patterns;
This question already has answers here:
When a function has a specific-size array parameter, why is it replaced with a pointer?
(3 answers)
Closed 7 years ago.
I'm trying to write a function that casts an array of ints into doubles. It takes in a constant pointer to the original int[] array (to avoid unwanted modifications?) and returns a pointer to an array of casted double[]. However, the code that I wrote doesn't seem to be working. Can anyone point out what's wrong with it?
#include <iostream>
using namespace std;
double* castToDouble(const int *input);
int main(){
int integers[] = {1,2,3,4};
double *doubles = castToDouble(integers);
cout << "numElements in doubles: " << sizeof(doubles)/sizeof(double) << endl;
for(int i = 0; i < sizeof(doubles)/sizeof(double); i++){
cout << doubles[i] << endl;
}
return 0;
}
double* castToDouble(const int *input){
// Obtain the number of elements in input.
int numElements = sizeof(input)/sizeof(int);
double *doubleAry = new double[numElements];
cout << "numElements in input: " << numElements << endl;
for(int i = 0; i < numElements; i++){
doubleAry[i] = static_cast<double>(input[i]);
}
return doubleAry;
}
The output of the program is the following:
numElements in input: 2
numElements in doubles: 1
1
The numElements' calculated seem to be arbitrary too. I'm pretty new to c++ and am unable to pinpoint the problem. Thanks in advance.
As you marked it C++, I thought this might be more idiomatic:
#include <vector>
#include <algorithm>
std::vector<double> CastToDouble(std::vector<int> const & ints)
{
auto doubles = std::vector<double>(ints.size());
std::transform(ints.begin(), ints.end(), doubles.begin(), [](int value) -> double {
return static_cast<double>(value);
});
return doubles;
}
int main(int argc, char* argv[])
{
auto values = std::vector<int>() = {
1, 2, 3, 4
};
auto doubles = CastToDouble(values);
}