Search code examples
c++arrayspointersglobal-variables

Copying one int array to another C++


Was trying to write a program which converts the value`s from one assigned array to another unassigned one. The code i wrote:

#include "stdafx.h";
#include <iostream>;

using namespace std;

int a[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int j[10];

int copy_array(int *p1, int n);
int *p2, *p2;

int main() {

    for (int l = 0; l < 10; l++) {
        cout << a[l] << endl;
    }

    copy_array(a, 10);

    for (int i = 0; i < 10; i++) {
        j[i] = &p2;
        cout << j[i] << endl;
    }

    system("PAUSE");
    return 0;
}

int copy_array(int *p1, int n) {
    while (n-- > 0) {
        *p1 = *p2;
            *p1++;
        *p2++;
    }
}

Im using the Microsoft visual studio platform and the error i got was "There is no context in which this conversion is possible". Why i cant use this int convert path? how can i fix and connect the 2 arrays using int type conversion(if its possible)?

What i tried was manipulating the local function copy_array so it makes the conversion using the addresses of the j[10] array integers, but this gave me another error. Any support and advice would be appreciated.


Solution

  • These are some notes on your code:

    1. you have redundant p2 declaration:int *p2, *p2;. Also you need to initialize it. so make it: int *p2 = j; (in fact, you don't actually need to use this global variable - you can achieve the same effect by passing j as necessary).
    2. Inside your copy function, your assignment should be in reverse: *p2 = *p1; not *p1 = *p2; - the right-hand side is assigned to the left hand side.
    3. When printing j, you do not need j[i] = &p2; which alters j's contents.
    4. It is better to define the arrays inside the function not in the general scope.

    Correct them and your code should work fine.

    However, You do not need pointers to do this at all.

    Consider the following code and compare it to yours:

    #include <iostream>
    using namespace std;  
    
    void copy_array(int [], int [], int);
    void print_array(int [], int);
    
    int main() {
    
        int a[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        int j[10];
    
        print_array(a,10);
        copy_array(a, j, 10);
        print_array(j,10);
        return 0;
    }
    
    void copy_array(int s[], int d[], int n) {
        for (int i = 0; i < n; i++)
            d[i] = s[i];   
    }    // s for source & d for destination
    
    void print_array(int arr[], int n) {
        for (int i = 0; i < n; i++)
            cout << arr[i] << " ";
        cout << "\n\n";
    }