Resolving Dynamic Memory Allocation problem in array function [duplicate] - c++

This question already has answers here:
How to return local array in C++?
(12 answers)
Why aren't variable-length arrays part of the C++ standard?
(10 answers)
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 7 months ago.
I am learning to apply C++ pointers by creating a program that can multiply the combination of numbers from two arrays and pass the list of numbers in a newly created array. But the result produced from the program outputs garbage values in the result, probably a dangling pointer problem.
Here's my code:
#include <iostream>
using namespace std;
void print(int *array[], size_t array_size);
int *apply_all(int array1[], size_t size1, size_t array2[], int size2);
void print(int array[], size_t array_size) {
cout << "[ ";
for (size_t i{0}; i < array_size; ++i)
cout << array[i] << " ";
cout << "]" << endl;
}
int *apply_all(int array1[], size_t size1, int array2[], int size2) {
int new_array [size1 * size2] {};
int *array_ptr {new_array};
for (size_t i_1{0}; i_1 < size1; ++i_1) {
for (size_t i_2{0}; i_2 < size2; ++i_2) {
*array_ptr = array1[i_1]*array2[i_2];
array_ptr++;
}
}
return array_ptr;
}
int main() {
const size_t array1_size {5};
const size_t array2_size {3};
int array1 [] {1,2,3,4,5};
int array2 [] {10,20,30};
cout << "Array 1: ";
print(array1, array1_size);
cout << "Array 2: ";
print(array2, array2_size);
int *results = apply_all(array1, array1_size, array2, array2_size);
constexpr size_t results_size {array1_size * array2_size};
cout << "Result: ";
print(results, results_size);
}
Output:
Array 1: [ 1 2 3 4 5 ]
Array 2: [ 10 20 30 ]
Result: [ 0 1249712272 500 -353954405 32759 14 0 3 0 5 0 562035404 117 58 0 ]
Do I have to do something with dynamic memory allocation?

Related

How is this array is altering its value? [duplicate]

This question already has answers here:
Are passing char array by (char* ar) and (char ar[ ]) same? c++ [duplicate]
(1 answer)
What is array to pointer decay?
(11 answers)
Closed 1 year ago.
This is a post from https://www.geeksforgeeks.org about reversing an array.
In the rvereseArray() function, array is not using any pointer. But still in the main() function, when the rvereseArray() function is called and the arr is passed, it is able to alter the value. how?
// Iterative C++ program to reverse an array
#include <bits/stdc++.h>
using namespace std;
/* Function to reverse arr[] from start to end*/
void rvereseArray(int arr[], int start, int end)
{
while (start < end)
{
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
/* Utility function to print an array */
void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
/* Driver function to test above functions */
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
// To print original array
printArray(arr, n);
// Function calling
rvereseArray(arr, 0, n-1);
cout << "Reversed array is" << endl;
// To print the Reversed array
printArray(arr, n);
return 0;
}

Dynamic allocation not working for global integer pointer

My Code:
#include <iostream>
#include <cstdlib>
using namespace std;
int *p;
void fun(int *arr, int n)
{
p = (int *)malloc(sizeof(int) * (n + 1));
cout << sizeof(p) / sizeof(int) << " " << sizeof(p) << " " << sizeof(int) << endl;
}
int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
fun(arr, n);
return 0;
}
Input:
4
2 1 4 3
Output:
2 8 4
Expected Output:
5 20 4
The code returns an incorrect value of the size which is being allocated to the array using malloc. I identified this problem when I used memset(p, -1, sizeof(p)))and the array was incorrectly initialized. Please help. Thanks in advance.
Because p is a pointer sizeof(p) will return 8 (or 4 on 32 bit systems). Because that is the size used by p. The memory size used by the structure p points to is another story

Pass subarray to function

I have a function to which I need to pass an array.
But I don't want to pass the entire array (e.g., valid indices from array[0] to array[size-1]), but a subarray (e.g., valid indices starting at array[5] to array[size-1]).
Is there a way to do that in C++?
You can transfer array to function parameter below
void Foo(int* arr, int length);
//call Foo
Foo(&a[0], length); //or
Foo(a, length);
you can also transfer a certain range of array.
Foo(&a[1], length);
Foo(a + 1, length);
Just, simple code.
#include <iostream>
void Print(int* arr, int length)
{
for(int i=0; i < length; i++)
{
std::cout << *(arr + i) << ", ";
}
std::cout << std::endl;
}
int main()
{
int a[5] = {1,2,3,4,5};
//type A
Print(&a[0], sizeof(a)/sizeof(int)); //print all element of a
Print(&a[1], 3); //print 2,3,4
//type B
Print(a, sizeof(a)/sizeof(int)); //print all element of a
Print(a + 1, 3); //print 2,3,4
getchar();
return 0;
}
Quoted comment by n.m.:
You cannot pass an array to a function. When you try to, you actually pass the address of the first element of the array. If you need a subarray that starts at 5, you just pass the address of the fifth elements. You shouldn't be using C-style arrays anyway. Use std::vector and iterators, this is the C++ way.
As indicated, you can add an offset to the array base pointer (and subtract from the passed arraysize accordingly).
Or pass begin and end (one past the end) pointers of the array to the function to achieve an "iterator-style" implementation.
But as you are programming C++, please consider to use std::vector.
Example:
#include <iostream>
void foo(int arr[], int size) {
for (int i = 0; i < size; i++)
std::cout << arr[i] << ' ';
}
void bar(int* begin, int* end) {
while (begin != end)
std::cout << *begin++ << ' ';
}
int main() {
int arr[] = {0,1,2,3,4,5,6,7,8,9};
int size = sizeof(arr)/sizeof(*arr);
// pass entire array
foo(arr, size);
//bar(arr, arr+size);
std::cout << '\n';
// pass array starting at index 5
foo(arr+5, size-5);
//bar(arr+5, arr+size);
std::cout << '\n';
}
The output is:
$ g++ test.cc && ./a.out
0 1 2 3 4 5 6 7 8 9
5 6 7 8 9

C++: passing and returning pointers to arrays - code not working [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)
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);
}

Printing array in C++ error [duplicate]

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;
}