指针未传递的新数组值

时间:2017-10-12 01:09:01

标签: c++ arrays pointers

我有一个类赋值,我需要创建一个动态数组,在其中存储两个指针,然后交换它们。

我差不多完成了,但由于某种原因,我无法将新存储的值传递给数组。我知道问题是最后两行代码,我知道这是错误的,但我尝试修复的代码不会编译。

when(mockMapper.reader(any(ObjectNode.class))).thenReturn(objectReader));

3 个答案:

答案 0 :(得分:0)

变量" a"和" b"在exchange()函数内部正在更新,但你应该更新函数外部的数组,这更有意义并且工作正常(你调用函数,它会更改变量,然后在返回后更新数组)。这是更新的代码:

#include <iostream>
#include <cstdio>

using namespace std;

// Function prototype
void exchange(int*, int*, int* Arr[]);

int main()
{
    int* Arr = new int[5], i;  //Declare Dynamic Array

    cout << "Enter Number of Elements : " << endl;
    for (int i = 0; i < 5; i++) //setting all values in the Array to Zero.
    {
        printf("Number %d: ", i);
        scanf("%d", Arr + i); 
    }

    cout << endl;

    int a = Arr[3], b = Arr[4];

    cout << "The integers before swap : " << endl << endl;
    cout << "Fourth integer equals : " << Arr[3] << endl;
    cout << "Fifth integer equals : " << Arr[4] << endl << endl;

    exchange(&a, &b);
    Arr[3] = a;
    Arr[4] = b;

    cout << "The integers after swap : \n" << endl;
    cout << "Fourth integer equals : " << Arr[3] << endl;
    cout << "Fifth integer equals : " << Arr[4] << endl;
    delete[] Arr;  //Delete Dynamic Array

    system("pause");
    return 0;
}

void exchange(int* a, int* b)
{
    cout << "Please Enter two new intergers \n" << endl;
    cin >> *a;
    cout << endl;
    cin >> *b;
    cout << endl;
}

答案 1 :(得分:0)

#include <iostream>
using namespace std;

// Function prototype
void exchange(int*, int*, int* Arr[]);

int main()
{    
int* Arr = new int[5], i;  //Declare Dynamic Array
cout << "Enter Number of Elements : " << endl;
for (int i = 0; i < 5; i++) //setting all values in the Array to Zero.
    scanf("%d", Arr + i); 
    cout << endl;

int a = Arr[3], b = Arr[4];

cout << "The integers before swap : " << endl << endl;
cout << "Fourth integer equals : " << Arr[3] << endl;
cout << "Fifth integer equals : " << Arr[4] << endl << endl;

exchange(&a, &b, &Arr);

cout << "The integers after swap : \n" << endl;
cout << "Fourth integer equals : " << Arr[3] << endl;
cout << "Fifth integer equals : " << Arr[4] << endl;
delete[] Arr;  //Delete Dynamic Array

system("pause");
return 0;
}

void exchange(int* a, int* b, int* Arr[]) {
cout << "Please Enter two new intergers \n" << endl;
cin >> *a;
cout << endl;
cin >> *b;
cout << endl;
Arr[0][3] = *a; //These are the problem here, when I try *a it doesn't work
Arr[0][4] = *b;
}

答案 2 :(得分:0)

参数int* Arr[]exchange声明一个数组指针(实际上是一个指向指针的指针;&#34;数组&#34;只是一个约定) 。解决此问题,然后从通话中的&中删除&Arr

要明确,这可能不会使您的程序(其要求不明确)正确;它只是你所指示的线条的修复,使它们具有你想要的效果。