How can I modify values of an array passed to a function? - c++

I'm a C++ beginner and I'm stuck on my course assignment because I can't wrap my head around how to modify values of an array passed to a function.
Honestly, we haven't reached the topic about arrays yet in class, but I recall some basic functionalities related to them and I wanted to solve the exercise using arrays because it's surely a smarter way to do it then the easy version of the assignment without them (that I've already solved). I've looked online for some references but clearly I'm missing something important.
The assignment states:
In this exercise you’ll investigate a simple scheme for encrypting and decrypting data. A company that wants to send data over the Internet has asked you to write a program that will encrypt the data so that it may be transmitted more securely. All the data is transmitted as four-digit integers. Your application should read a four-digit integer entered by the user and encrypt it as follows:
Replace each digit with the result of adding 7 to the digit and getting the remainder after dividing the new value by 10.
Then swap the first digit with the third, and swap the second digit with the fourth.
Then print the encrypted integer.
And my attempt is this:
main.cpp
#include "encrypt.h"
#include <iostream>
const size_t size{4};
int main () {
int arrEncrypt[size] = {1, 2, 3, 4};
swap(arrEncrypt[size]);
encrypt(arrEncrypt[size]);
printArr(arrEncrypt[size]);
}
encrypt.h
#ifndef ENCRYPT_H
#define ENCRYPT_H
void encrypt(int a[]);
void swap(int a[]);
void printArr(int a[]);
#endif
encrypt.cpp
#include <iostream>
#include "encrypt.h"
const size_t num{4};
// Replace each digit with the result of adding 7 to the digit and getting the remainder after dividing the new value by 10.
void encrypt(int arr[::num]) {
for (int k = 0; k < ::num; k++) {
arr[k] = (arr[k] + 7) % 10;
}
}
// Then swap the first digit with the third, and swap the second digit with the fourth.
void swap(int arr[::num]) {
int box[1] = {0};
for (int k = 0; k < (::num / 2); k++) {
box[1] = arr[k];
arr[k] = arr[k+2];
arr[k+2] = box[1];
}
box[1] = arr[0];
arr[0] = arr[2];
arr[2] = box[1];
box[1] = arr[1];
arr[1] = arr[3];
arr[3] = box[1];
}
// Then print the encrypted integer.
void printArr(int arr[::num]) {
for (int k = 0; k < ::num; k++) {
std::cout << arr[k] << " ";
}
}
The swap function has some problems in the algorithm probably because I tried printing the for loop output and I get just one random value, while the bit manually written is working fine. I don't know why.
This program clearly doesn't work because every time I pass the array to a function it is always the one declared in main and not an array modified by the functions. I tried pointing to the array passed to the functions but I think I messed it up because I got a bunch of errors - moreover, I've read that taking the address of a built-in array to pass it to a function is not needed and I can simply pass the built-in array’s name because the called function can modify all the elements of an array in the caller, unless the function precedes the corresponding built-in array parameter with const to indicate that the elements should not be modified. But I don't get why in my program it doesn't work.
Thanks in advance for anyone who would take their time to help me out, I really appreciate it.

An array can't be passed to a function by value, only by reference or pointer. In your case, a parameter like int a[] is really just syntax sugar for a pointer int *a. But you are not actually calling the functions with a pointer, you are indexing into arrEncrypt and passing an individual int instead (using an index that is out of range!).
Get rid of the array indexing at the call sites. An array decays into a pointer to its 1st element when it is referred to by just its name.
Also, such parameters don't carry size information, so you have to pass the array size explicitly in a separate parameter.
Try this instead:
#include "encrypt.h"
const size_t size{4};
int main () {
int arrEncrypt[size] = {1, 2, 3, 4};
swap(arrEncrypt, size);
encrypt(arrEncrypt, size);
printArr(arrEncrypt, size);
}
encrypt.h
#ifndef ENCRYPT_H
#define ENCRYPT_H
void encrypt(int a[], int size);
void swap(int a[], int size);
void printArr(int a[], int size);
#endif
encrypt.cpp
#include <iostream>
#include <stdexcept>
#include "encrypt.h"
// Replace each digit with the result of adding 7 to the digit and getting the remainder after dividing the new value by 10.
void encrypt(int arr[], int size) {
if (!arr || size < 0) throw invalid_argument("");
for (int k = 0; k < size; k++) {
arr[k] = (arr[k] + 7) % 10;
}
}
// Then swap the first digit with the third, and swap the second digit with the fourth.
void swap(int arr[], int size) {
if (!arr || size < 4) throw invalid_argument("");
int box;
for (int k = 0; k < (size / 2); k++) {
box = arr[k];
arr[k] = arr[k+2];
arr[k+2] = box;
}
box = arr[0];
arr[0] = arr[2];
arr[2] = box;
box = arr[1];
arr[1] = arr[3];
arr[3] = box;
}
// Then print the encrypted integer.
void printArr(int arr[], int size) {
if (!arr) throw invalid_argument("");
for (int k = 0; k < size; k++) {
std::cout << arr[k] << " ";
}
}
That being said, consider using std::vector instead, eg:
#include "encrypt.h"
int main () {
std::vector<int> arrEncrypt = {1, 2, 3, 4};
swap(arrEncrypt);
encrypt(arrEncrypt);
printArr(arrEncrypt);
}
encrypt.h
#ifndef ENCRYPT_H
#define ENCRYPT_H
#include <vector>
void encrypt(std::vector<int> &a);
void swap(std::vector<int> &a);
void printArr(const std::vector<int> &a);
#endif
encrypt.cpp
#include <iostream>
#include <utility>
#include <stdexcept>
#include "encrypt.h"
// Replace each digit with the result of adding 7 to the digit and getting the remainder after dividing the new value by 10.
void encrypt(std::vector<int> &arr) {
for (size_t k = 0; k < arr.size(); k++) {
arr[k] = (arr[k] + 7) % 10;
}
}
// Then swap the first digit with the third, and swap the second digit with the fourth.
void swap(std::vector<int> &arr) {
if (arr.size() < 4) throw invalid_argument("");
for (size_t k = 0; k < (a.size() / 2); k++) {
std::swap(arr[k], arr[k+2]);
}
std::swap(arr[0], arr[2]);
std::swap(arr[1], arr[3]);
}
// Then print the encrypted integer.
void printArr(const std::vector<int> &arr) {
for (size_t k = 0; k < arr.size(); k++) {
std::cout << arr[k] << " ";
}
}
Or std::array, eg:
#include "encrypt.h"
int main () {
std::array<int, size> arrEncrypt = {1, 2, 3, 4};
swap(arrEncrypt);
encrypt(arrEncrypt);
printArr(arrEncrypt);
}
encrypt.h
#ifndef ENCRYPT_H
#define ENCRYPT_H
#include <array>
#include <iostream>
#include <utility>
// Replace each digit with the result of adding 7 to the digit and getting the remainder after dividing the new value by 10.
template<typename T, size_t N>
void encrypt(std::array<T, N> &arr) {
for (size_t k = 0; k < N; k++) {
arr[k] = (arr[k] + 7) % 10;
}
}
// Then swap the first digit with the third, and swap the second digit with the fourth.
template<typename T, size_t N>
void swap(std::array<T, N> &arr) {
if (N < 4) throw invalid_argument("");
for (size_t k = 0; k < (N / 2); k++) {
std::swap(arr[k], arr[k+2]);
}
std::swap(arr[0], arr[2]);
std::swap(arr[1], arr[3]);
}
// Then print the encrypted integer.
template<typename T, size_t N>
void printArr(const std::array<T, N> &arr) {
for (size_t k = 0; k < N; k++) {
std::cout << arr[k] << " ";
}
}
#endif

The arguments arrEncrypt[size] in the function main() is bad because
It is out-of-range because the array arrEncrypt has only size elements and its valid indice are 0 to size-1.
The functions are expecting pointers, but an integer is passed.
The element box[1] used in the function swap() is out-of-range because the array box has only one element. Since it looks you are using only the element box[1] from the array box, you should stop using array here and instead of that you should use simple variable box.
In the function main(), you should pass the array (or a pointer to the first element of the array converted from the array) to the function:
int main () {
int arrEncrypt[size] = {1, 2, 3, 4};
swap(arrEncrypt);
encrypt(arrEncrypt);
printArr(arrEncrypt);
}
In the function swap(), you should stop using out-of-range "element":
void swap(int arr[::num]) {
int box = 0;
for (int k = 0; k < (::num / 2); k++) {
box = arr[k];
arr[k] = arr[k+2];
arr[k+2] = box;
}
box = arr[0];
arr[0] = arr[2];
arr[2] = box;
box = arr[1];
arr[1] = arr[3];
arr[3] = box;
}

Related

How do you return an array that has multiple values from a function? C++

I am trying to return a certain array from a function that when called, assigns value to the array
The function should go something like this:
int arr[10];
int values[10] = {1,2,3,4,5,6,7,8,9};
for (int i =0; i<10; i++)
{
arr[i] = values[i];
}
How do I translate this code into a function?
using namespace std;
As far I know, you shouldn't be looking to return an array from a function... like, ever.
What I would do instead is pass the names of the arrays to the function and have it process the contents in whatever way you need it to. In your case, you're just copying them so something like this should work:
#include <iostream>
using namespace std;
void copy_array (const int [], int []); //function prototype
int main()
{
//Your arrays
int arr[10];
int values[10] = {1,2,3,4,5,6,7,8,9};
//Function call
copy_array(values, arr);
//Display contents of array
for(int i =0; i<10; i++){
cout << arr[i] << " " ;
}
return 0;
}
//Function definition
void copy_array (const int values[], int arr[]){
for (int i =0; i<10; i++){
arr[i] = values[i];
}
}
Output
1 2 3 4 5 6 7 8 9 0
Also, your array size should be a constant integer variable.
you probably don't want to return arrays like never, because it could mean a lot of useless copy, which slows down your program, but
you could always write a function that copies values from one array to another
#include <iostream>
void assignarray(int *dest, int *src, size_t size)
{
for (size_t i = 0; i < size; ++i)
{
dest[i] = src[i];
}
}
int main()
{
int arr[10];
int values[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
assignarray(arr, values, sizeof(values) / sizeof(int));
for (size_t i = 0; i < 10; i++)
{
std::cout << values[i] << " ";
}
}
output:
1 2 3 4 5 6 7 8 9 10
Return type of a function cannot be an array.
However, array can be member of a class, and class can be return type of a function, so it is possible to return a class object which wraps the array. The standard library has a template for such array wrapper. It is called std::array.
That said, returning an array (wrapped within a class) is not necessarily a good design. Sometimes it is better to let the caller create the container - and indeed, they can choose the type of the container that they wish to use - and pass that into a template function to be filled. Here is an example of accepting a range:
template<class Range>
void fill(Range& r) {
assert(std::ranges::distance(r) == 10);
int values[10] = {1,2,3,4,5,6,7,8,9};
int i = 0;
for (auto& e : r)
{
e = values[i++];
}
}
// example
int arr[10];
fill(arr);

Function to delete an element from an array not working

I wanted to write a function which upon being called deletes an element from an array given that the parameters passed in the deleteArray function were the array, its length and the value of the element to be deleted.
Tried breaking out of the for loop while transversing through the array if the element was found and then tried using i's value in another for loop to replace the current elements with their next element.
like array[j] = array[j + 1]
Here is the code:
#include <iostream>
using namespace std;
void deleteElement(int[], int, int);
int main() {
int array1[] = { 1, 4, 3, 5, 6 };
int length = sizeof(array1) / sizeof(array1[0]); //For length of array
deleteElement(array1, length, 4);
cout << "\nIn main function\n";
for (int i = 0; i < length; i++) {
cout << array1[i];
}
return 0;
}
void deleteElement(int array2[], int length, int element) {
int i = 0;
for (int i; i < length; i++) {
if (array2[i] == element) {
for (int j = i; j < length; j++) {
array2[j] = array2[j + 1];
}
break;
}
}
if (i == (length - 1)) {
cout << ("Element doesn't exist\n");
}
cout << "Testing OP in deleteElement\n";
for (int i = 0; i < length; i++) {
cout << array2[i];
}
}
Expected:
Testing OP in deleteElement
14356
In main function
1356
Actual:
Testing OP in deleteElement
14356
In main function
14356
The problem is rather silly:
At the beginning of deleteElement(), you define i with int i = 0;, but you redefine another variable i as a local index in each for loop. The for loop introduces a new scope, so the int i definition in the first clause of the for loop defines a new i, that shadows the variable with the same name defined in an outer scope.
for (int i; i < length; i++) {
And you do not initialize this new i variable.
There are 2 consequences:
undefined behavior in the first loop as i is uninitialized. The comparison i < length might fail right away.
the test if (i == (length - 1)) { tests the outer i variable, not the one that for iterated on. Furthermore, the test should be if (i == length) {
There are other issues:
the nested for loop iterates once too many times: when j == length - 1, accessing array[j + 1] has undefined behavior.
you do not update length, so the last element of the array is duplicated. You must pass length by reference so it is updated in the caller's scope.
Here is a corrected version:
#include <iostream>
using namespace std;
void deleteElement(int array2[], int& length, int element);
int main() {
int array1[] = { 1, 4, 3, 5, 6 };
int length = sizeof(array1) / sizeof(array1[0]); //For length of array
deleteElement(array1, &length, 4);
cout << "\nIn main function\n";
for (int i = 0; i < length; i++) {
cout << array1[i] << " ";
}
return 0;
}
void deleteElement(int array2[], int& length, int element) {
int i;
for (i = 0; i < length; i++) {
if (array2[i] == element)
break;
}
if (i == length) {
cout << "Element doesn't exist\n";
} else {
length -= 1;
for (; i < length; i++) {
array2[i] = array2[i + 1];
}
}
cout << "Testing OP in deleteElement\n";
for (i = 0; i < length; i++) {
cout << array2[i] << " ";
}
}
If you use the algorithm function std::remove, you can accomplish this in one or two lines of code without writing any loops whatsoever.
#include <algorithm>
#include <iostream>
void deleteElement(int array2[], int& length, int element)
{
int *ptr = std::remove(array2, array2 + length, element);
length = std::distance(array2, ptr);
}
int main()
{
int array1[] = { 1, 4, 3, 5, 6 };
int length = sizeof(array1) / sizeof(array1[0]); //For length of array
deleteElement(array1, length, 4);
for (int i = 0; i < length; ++i)
std::cout << array1[i];
}
Output:
1356
Note that we could have written the deleteElement function in a single line:
void deleteElement(int array2[], int& length, int element)
{
length = std::distance(array2, std::remove(array2, array2 + length, element));
}
Basically, std::remove moves the removed element to the end of the sequence, and returns a pointer to the beginning of the removed elements.
Thus to get the distance from the beginning of the array to where the removed elements are located, usage of std::distance is done to give us our new length.
To remove only the first found element, std::find can be used, and then std::copy over the elements, essentially wiping out the item:
void deleteElement(int array2[], int& length, int element)
{
int *ptr = std::find(array2, array2 + length, element);
if ( ptr != array2 + length )
{
std::copy(ptr+1,array2 + length, ptr);
--length;
}
}
int main()
{
int array1[] = { 1, 4, 3, 5, 4, 6, 9 };
int length = sizeof(array1) / sizeof(array1[0]); //For length of array
deleteElement(array1, length, 4);
for (int i = 0; i < length; ++i)
std::cout << array1[i];
}
Output:
135469
There is no need for multiple loops in deleteElement. Additionally, your removal will fail to remove all elements (e.g. 4 in your example) if your array contains more than one 4, e.g.
int array1[] = { 1, 4, 3, 4, 5 };
You can simplify your deleteElement function and handle removing multiple occurrences of element simply by keeping a count of the number of times the element is found and by using your counter as a flag to control removal, e.g.:
void deleteElement(int array2[], int& length, int element)
{
int found = 0; /* flag indicating no. element found */
for (int i = 0; i < length; i++) { /* iterate over each element */
if (array2[i] == element) { /* check if matches current */
found += 1; /* increment number found */
continue; /* get next element */
}
if (found) /* if matching element found */
array2[i-found] = array2[i]; /* overwrite elements to end */
}
length -= found; /* update length based on no. found & removed */
}
Updating your example main() to show both pre-delete and post-delete, you could do something like the following:
int main (void) {
int array1[] = { 1, 4, 3, 4, 5 };
int length = sizeof array1 / sizeof *array1; //For length of array
cout << "\nBefore Delete\n";
for (int i = 0; i < length; i++)
cout << " " << array1[i];
cout << '\n';
deleteElement(array1, length, 4);
cout << "\nAfter Delete\n";
for (int i = 0; i < length; i++)
cout << " " << array1[i];
cout << '\n';
}
Example Use/Output
Which in the case where you array contains 1, 4, 3, 4, 5 would result in:
$ ./bin/array_del_elem
Before Delete
1 4 3 4 5
After Delete
1 3 5
While you are using an array of type int (of which there are many in both legacy and current code), for new code you should make use of the containers library (e.g. array or vector, etc...) which provide built in member functions to .erase() elements without you having to reinvent the wheel.
Look things over and let me know if you have further questions.
This is because the length of the array is never updated after deleting. Logically the length should decrease by 1 if the element was deleted.
To fix this, either
Pass the length by reference and decrease it by 1 if the element is actually deleted. OR
Return from the deleteElement some value which indicates that the element was deleted. And based of that, decrease the value of length in the main function.
Recalculating the array length will not help because the element is not actually deleted in memory. So the memory allocated to he array remains same.
Other issues:
The first for loop in deleteElement should run till j < length - 1.
The for loop creates a local variable i, which shadows the i variable in outer scope, so the outer i is never updated and always remains = 0

getting the nth largest number

I am trying to get the nth largest number of an array, I tried to sort the array then access the nth number by indexing; I have written this code:
#include <iostream>
using namespace std;
int largest(int a[],int k){
for (int i=0;i<=(sizeof(a)/sizeof(*a));i++){
for (int j=i+1;j<=(sizeof(a)/sizeof(*a));j++){
if(a[j]>a[i]){
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
return a[k-1];
}
int main()
{
int a[]={3,2,1,0,5,10};
int m=largest(a,4);
cout<<m<<endl;
return 0;
}
and when I print out m it appears to be 5 while it is expected to be 2, when I tried to replace int m=largest(a,4); with m=largest(a,1); it printed 2 so it appears that he prints the index of the array a but without sorting it, any idea?
The problem lies in the use of sizeof(a)/sizeof(*a) to get the number of elements of the array. sizeof(a) is the size of a pointer.
You need to pass the size of the array to the function.
int largest(int a[], int size, int k){
for (int i=0;i<size;i++){
for (int j=i+1;j<size;j++){
...
}
}
}
and call it with
int m = largest(a, 6, 4);
There are three problems with your code.
First, when you pass the array as an argument to your function, it decays into a pointer. So the function can never know the size of the array without additional information. It is main()'s job to find the size of the array and pass that information along to largest().
Second, you have an off-by-one error in your code, because you are attempting to iterate from 0 to the number of elements in the array.
The following will work:
#include <iostream>
using namespace std;
int largest(int a[],int k, int n){
for (int i = 0; i < n; i++){
for (int j = i + 1; j < n; j++){
if (a[j] > a[i]){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a[k-1];
}
int main()
{
int a[] = {3, 2, 1, 0, 5, 10};
int k = 4;
int m = largest(a, k, sizeof a/ sizeof *a);
cout << m << endl;
}
At last but not least, you have nasty side effects in your function. If you have a function that is supposed to find the largest element of the array, it shouldn't modify the entire array in order to do so.
You can make a copy of the original array and sort it. Or you can implement a k-element sort algorithm. Either way you shouldn't change user data just to find some statistic from it.
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int a[]={3,2,1,0,5,10};
std::sort(a, a+6, greater<int>() ); // Sort an array of 6 elements in greatest-first order.
cout<<a[3]<<endl; // Show the 4th element from the front.
return 0;
}
UPD: There are STL algorithm to use: std::nth_element.
#include <iostream>
#include <algorithm>
int main(){
int arr[] = {54, 897, 87, 4, 6,987};
size_t length = 6, k = 3;
std::cout<<std::nth_element(arr, arr + k, arr + length, std::greater<int>());
}
Also, if you want to implement it by yourselt you can do such thing based on quick sort:
#include <iostream>
#include <algorithm>
template<class T>
T largest_k(T* a, size_t left, size_t right, size_t k) {
if(left>=right)
return a[k-1];
size_t i = left, j = right;
T middle = a[ i + (j-i) / 2 ];
do {
while ( a[i] > middle ) i++;
while ( a[j] < middle ) j--;
if (i <= j) {
std::swap(a[i], a[j]);
i++; j--;
}
} while ( i<=j );
// We need to go deeper only for needed part of a
if ( k<=j+1 )
return largest_k(a, left, j, k);
if ( k>= i )
return largest_k(a, i, right, k);
}
int main()
{
int arr[] = {54, 897, 87, 4, 6,987};
size_t length = 6, k = 3;
std::cout<<largest_k<int>(arr, 0, length-1, k);
}

C++ Program crashing when trying to rearrange array

I'm still relatively new to c++. I am trying to write a program that takes an array of numbers and reverses the order of those numbers in the array with a function. The program is as follows:
#include <iostream>
using namespace std;
void reverse(int *array, int size);
int main() {
int Array[] = { 1, 2, 3, 4, 5 };
int size = sizeof(Array) / 4;
reverse(Array, size);
return 0;
}
void reverse(int *array, int size) {
int Array2[5];
for (int i = 0; i < size; i++) {
Array2[i + size] = array[i];
array[i + size] = Array2[i + size];
};
}
When I run this program, it crashes and I'm not sure why. If anyone can help my figure out why it would be much appreciated. Thank you.
Zenith has it, but there are a few points and quick hacks worth noting to help you out.
#include <iostream>
//using namespace std; don't need this, and using namespace std is overkill and often
// causes problems. It pulls in a lot of stuff that may conflict, case in point
// std::reverse now becomes reverse. Which reverse will you get? Your reverse or the standard
// library's reverse? Only pull in what you need, for example
using std::cout; // still not used, but makes a good example.
void reverse(int *array, int size)
{
// no need for the other array and another loop. You can swap each element for
//it's counterpart in the upper half of the array.
for (int i = 0; i < size /2 ; i++) // only need to go half way. Other half was
// already swapped doing the first half.
{
int temp = array[i]; // store a temporary copy of element i
array[i] = array[size-1-i]; // replace element i with it's counterpart
// from the second half of the array
array[size-1-i] = temp; // replace the counterpart of i with the copy of i
// or call std::swap(array[i], array[size-1-i]);
};
}
int main() {
int Array[] = { 1, 2, 3, 4, 5 };
// int size = sizeof(Array) / 4; using 4 here can trip you up on a computer with
// a different sized int
int size = sizeof(Array) / sizeof(Array[0]);
// dividing the size of the array by the size of an element in the array will always
// get you the correct size
reverse(Array, size);
return 0;
}
Array2[i + size]
You're accessing out-of-bounds, no matter the value of i.
You probably meant Array2[size - 1 - i] to iterate the array backwards. (size - 1 is the index of the last element.)
by using swap you will get a much nicer solution which is also more efficient
void reverse(int *array, int size) {
for (int i = 0; i < size/2; i++) {
std::swap(array[i],array[size-1-i]);
};
}
When you say int size = sizeof(Array) / 4;, size is now (5 * sizeof(int)) / 4. That's how the sizeof operator works (at least when applied to arrays).
So size is probably 5, assuming a 4-byte int. Now, you get to reverse and its argument size is also 5.
You get to the for loop, and even at the first iteration, you have Array2[5] = /* something */ and array[5] = /* something */, both of which are buffer overruns.
Also, your reverse function doesn't actually do any reversing. Try this:
void reverse(int *arr, int size);
int main()
{
int Array[] = { 1, 2, 3, 4, 5 };
int size = sizeof(Array) / sizeof(int);
reverse(Array, size);
return 0;
}
void reverse(int *arr, int size)
{
int temp[5];
for (int i = 0; i < size; i++)
temp[size - 1 - i] = arr[i];
for (int i = 0; i < size; i++)
arr[i] = temp[i];
}

C++ basic array assignment is not working

So I have a function
f(int D[],int A[],int len){
for(int k = 0; k < len; k++)
D[k] = A[k];
and if I output D the numbers are all wrong. The function f is called with D initialised as int* D = new int[100000]; in the main function and A is all good because I output it in the function and it looks ok. So... can't understand where the problem is... I also tried memcpy(D+k,A+k,sizeof(int)); and it doesn't work.
Your loop works perfectly. The problem must be somewhere else in your code.
Here is an example program which copies the data in three different ways: a for loop, memcpy, and std::copy:
#include <algorithm>
#include <cstring>
#include <iostream>
#include <iterator>
void copy1(int D[], int A[], int len) {
for(int k = 0; k < len; k++)
D[k] = A[k];
}
void copy2(int D[], int A[], int len) {
std::memcpy(D, A, len*sizeof(int));
}
void copy3(int D[], int A[], int len) {
std::copy(A, A+len, D);
}
int main () {
int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int *d = new int[10];
std::ostream_iterator<int> out(std::cout, ",");
// First, print the initial values
std::copy(d, d+10, out);
std::cout << "\n";
// Next do the copies and print the values again
copy1(d, a, 10);
std::copy(d, d+10, out);
std::cout << "\n";
copy2(d, a, 10);
std::copy(d, d+10, out);
std::cout << "\n";
copy3(d, a, 10);
std::copy(d, d+10, out);
std::cout << "\n";
}
The output I get is:
0,0,0,0,0,0,0,0,0,0,
1,2,3,4,5,6,7,8,9,10,
1,2,3,4,5,6,7,8,9,10,
1,2,3,4,5,6,7,8,9,10,
Run your code in debugger and see if you do not have garbage in A[] in the first place (it could go wrong after function call). Also I suggest you pass reference (like int & D[] and const int & A[] — const to prevent altering of A).
Start with a minimal working example such as the following, then integrate your other code into it until something breaks. That’ll be the source of your error. Without more information, this is pretty much all I can tell you; when you encounter wrong values in a C++ program, you’re likely reading from an uninitialised variable. I suggest you try stepping through your program in a debugger such as GDB.
#include <algorithm>
#include <iostream>
#include <iterator>
void f(int D[], const int A[], int len){
for(int k = 0; k < len; k++)
D[k] = A[k];
}
int main(int argc, char** argv) {
int A[] = { 1, 2, 3, 4, 5 };
int D[5];
f(D, A, 5);
std::copy(A, A + 5, std::ostream_iterator<int>(std::cout, " "));
std::cout << '\n';
std::copy(D, D + 5, std::ostream_iterator<int>(std::cout, " "));
return 0;
}
Unless you have a very good reason to do so, prefer std::vector and std::array over raw arrays. Learning how arrays and pointers work is a good reason to use them, though.
I believe the problem is that you are passing in a pointer to an array
int* D = new int[100000];
however, your function takes two integer arrays, which is not the same as a pointer to an array.
Here's a SSCCE of a snippet that behaves like you want it:
#include <iostream>
using namespace std;
void f(int * d, int * a, int length){
for(int k = 0; k < length; k++){
d[k] = a[k];
}
}
int main() {
int* a = new int[9];
for(int i = 0; i < 9; i++){a[i] = i;}
int* d = new int[9];
f(d, a, 9);
for(int i = 0; i < 9; i++){
cout << d[i] << " ";
}
}